如何按时间间隔对数据进行分组?

时间:2015-05-28 11:17:00

标签: sql sql-server sql-server-2008

这是我的表:

SNO ID  TimeRecorded             LAT          LON      STATE    SPEED

7   0   2015-05-16 12:54:09.000 22.63006    88.362144   NULL    0
8   0   2015-05-16 12:55:09.000 22.63006    88.362144   NULL    0
9   1   2015-05-16 13:01:09.000 22.63006    88.362144   NULL    0
10  1   2015-05-16 13:05:09.000 22.63006    88.362144   NULL    0

如何只选择1小时的1条记录?,我想选择如下:

7   0   2015-05-16 12:54:09.000 22.63006    88.362144   NULL    0 and
10  1   2015-05-16 13:05:09.000 22.63006    88.362144   NULL    0

1 个答案:

答案 0 :(得分:2)

使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by cast(timerecorded as date), datepart(hour, timerecorded)
                                order by timerecorded
                               ) as seqnum
      from table t
     ) t
where seqnum = 1;

注意:这会返回每小时的第一条记录。如果您确实需要任意记录,则可以使用order by newid()而不是order by timerecorded