从结果集中选择第一个结果

时间:2015-08-30 03:44:04

标签: sql sql-server date datetime row-number

这是我的sql server查询结果,我只需要一分钟内的一个数据,现在第5分钟包含多个数据,就像第10分钟那样

我的sql server查询

select top 1000 val1,val2,timestamp
from VTagValue
where datepart(mi,timestamp)%5=0 `

83.2    83.4    2015-08-29 13:05:53.0730000 +08:00
83.2    83.4    2015-08-29 13:05:55.0730000 +08:00
83.2    83.4    2015-08-29 13:05:57.0730000 +08:00
84.0    84.2    2015-08-29 13:10:01.0730000 +08:00
84.0    84.2    2015-08-29 13:10:03.0730000 +08:00
84.0    84.2    2015-08-29 13:10:05.0730000 +08:00

预期结果

83.2    83.4    2015-08-29 13:05:53.0730000 +08:00
84.0    84.2    2015-08-29 13:10:01.0730000 +08:00

1 个答案:

答案 0 :(得分:3)

select val1, val2, timestamp 
from
(
select val1,val2, timestamp,
row_number() over(partition by datepart(mi,timestamp) order by timestamp) as rn 
from VTagValue 
where datepart(mi,timestamp)%5=0 
) t 
where rn = 1;

您可以使用row_number获取最早的时间戳一分钟。

编辑:根据OP的评论:

select val1, val2, timestamp 
from
(
select val1,val2, timestamp,
row_number() over(partition by datepart(hh,timestamp),datepart(mi,timestamp) 
                  order by timestamp) as rn 
from VTagValue 
where datepart(mi,timestamp)%5=0 
) t 
where rn = 1;