获取每个行号的最后一条记录

时间:2017-11-22 01:43:38

标签: sql sql-server

你有这样的书面查询:

select Customerid,orderDate, OrderNumber,
       DENSE_RANK() OVER (PARTITION BY Customerid ORDER BY orderDate) "rank"
from [order]

,这会产生结果:

 list customer order details

在这里,我想仅检索每个客户的最新购买:

1   2014-04-09 00:00:00.000 543141  6
2   2014-03-04 00:00:00.000 543056  4
3   2014-01-28 00:00:00.000 542986  7

如何使用sql查询实现此目的

1 个答案:

答案 0 :(得分:1)

使用子查询:

select o.*
from (select Customerid,orderDate, OrderNumber,
             DENSE_RANK() OVER (PARTITION BY Customerid ORDER BY orderDate DESC) as seqnum
      from [order] o
     ) o
where seqnum = 1;