I am new to SQL Server 2008 Express.
I have a table called Table1
which has First_Name
and Order_Date_Time
columns.
I want a SQL query which can select all records where First_Name
= Alex
and with max Order_Date_Time
. The table contains multiple dates with exact same date.
Does anyone know how to do this?
This should give you the correct result, and is pretty concise.
SELECT *
FROM Table1
WHERE Order_Date_Time = (select MAX(Order_Date_Time) FROM Table1) and First_name = 'Alex'
One simple method that has good performance with the right indexes is:
select t1.*
from table1 t1
where t1.order_date_time = (select max(tt1.order_date_time) from table1 tt1 where tt1.first_name = t1.first_name);
The right index in table1(name, order_date_time)
.
You can use row_number()
function :
select top (1) with ties t1.*
from table1 t1
where t1.First_Name = 'Alex'
order by row_number() over(partition by t1.first_name order by t1.order_date_time desc);
This will give all the records which contain Alex. That seems to be what you're looking from your comment.
SELECT First_Name, Order_Date_Time
FROM Table1
WHERE First_Name = 'Alex'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.