选择几天之内每天记录在表中的最后一个条目

时间:2020-04-14 16:54:16

标签: sql sql-server tsql date greatest-n-per-group

如何选择每天记录的最后一个条目?在此示例中,我需要过去5天中每天的最后订购商品编号和最后DateOrdered条目。这是我的桌子:

ItemNumber  |       DateOrdered
    1           2020-04-01 08:00:00.000
    3           2020-04-01 09:00:00.000
    5           2020-04-01 10:00:00.000
    4           2020-04-02 09:00:00.000
    6           2020-04-02 10:00:00.000
    7           2020-04-03 08:00:00.000
    3           2020-04-03 09:00:00.000
    2           2020-04-03 10:00:00.000
    5           2020-04-04 10:00:00.000
    8           2020-04-05 08:00:00.000
    2           2020-04-05 09:00:00.000
    8           2020-04-05 10:00:00.000

这是我需要的结果:

ItemNumber  |      DateOrdered
    5           2020-04-01 10:00:00.000
    6           2020-04-02 10:00:00.000
    2           2020-04-03 10:00:00.000
    5           2020-04-04 10:00:00.000
    8           2020-04-05 10:00:00.000

这是我所能接近的:

with tempTable as
(
  select
    *,
    row_number() over(partition by datediff(d, 0, DateOrdered) order by DateOrdered desc) as rn 
  from myTable
)
select *
from tempTable  
where rn = 1

1 个答案:

答案 0 :(得分:0)

您快到了。您只需要修复分区的定义,即可将属于同一天的所有行汇总在一起。

这应该做到:

with tempTable as
(
  select
    *,
    row_number() over(partition by cast(DateOrdered as date) order by DateOrdered desc) as rn 
  from myTable
)
select *
from tempTable  
where rn = 1