使用GROUP BY和MAX时如何选择其他表格字段?

时间:2017-05-24 19:05:47

标签: sql sql-server

我们说我有一个名为Orders的表,字段为CustomerId,EmployeeId,OrderDate

我想通过最新的OrderDate为每个CustomerId选择所有这些字段。

到目前为止,我已成功选择了CustomerId和OrderDate,但我不知道如何包含EmployeeId

 SELECT [CustomerId], MAX(OrderDate)
      FROM [Orders] 
      GROUP BY [CustomerId]
      ORDER BY [CustomerId]

1 个答案:

答案 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;