我们说我有一个名为Orders的表,字段为CustomerId,EmployeeId,OrderDate
我想通过最新的OrderDate为每个CustomerId选择所有这些字段。
到目前为止,我已成功选择了CustomerId和OrderDate,但我不知道如何包含EmployeeId
SELECT [CustomerId], MAX(OrderDate)
FROM [Orders]
GROUP BY [CustomerId]
ORDER BY [CustomerId]
答案 0 :(得分:1)
使用row_number()
:
select o.*
from (select o.*,
row_number() over (partition by customerid order by orderdate desc) as seqnum
from orders o
) o
where seqnum = 1;
这就是"传统"解。如果您有所有客户的列表,我喜欢使用cross apply
:
select o.*
from customers c cross apply
(select top 1 o.*
from orders o
where o.customerid = c.customerid
order by o.orderdate desc
) o;