我如何在sql中显示每个日期的最后一个事件

时间:2018-06-24 10:09:10

标签: sql sql-server

我有很多ID,每个ID有很多日期和小时,我想为每个ID显示第一个事件

表格例如:

id  eventid   time
1   2         1-1-2018 05:06:03:000
1   3         1-1-2018 08:05:54:000
1   4         1-1-2018 19:05:54:000
1   5         1-1-2018 24:05:54:000

我想做一个这样的表:

id  eventid   time
1   2         1-1-2018 05:06:03:000
1   5         1-1-2018 24:05:54:000

1 个答案:

答案 0 :(得分:1)

with cte as 
 (
   select *
     -- get min & max per date
     ,min(time) over (partition by cast(time as date)) as mintime
     ,max(time) over (partition by cast(time as date)) as maxtime
   from tab
 )
select *
from cte 
where time in (mintime,maxtime)