如何每小时选择一行数据?

时间:2017-03-24 15:15:32

标签: sql sql-server

我是sql的新手。 有些东西让我感到困惑,我每分钟获得数据,但我每小时或每2小时只需要一行。例如,当我从前一天选择数据时,它显示了1440行,我需要将它们减少到更少的行来制作一些图表。 提前谢谢。

当我使用此查询时:

select [Value],[Time] from [AbsoluteData] where [Sensor] = '5100' and [Time] >= dateadd(day,datediff(day,1,GETDATE()),0) AND[Time] < dateadd(day, datediff(day, 0, GETDATE()), 0)

我得到了:

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用row_number()这样每小时选择行:

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

我无法读取您的图片而您没有样本查询或示例数据,因此使用通用名称。

答案 1 :(得分:0)

以下查询会返回表格中的最后一小时数据

 SELECT  * FROM    TableName WHERE   myTime > DATEADD(HOUR, -1, GETDATE())

答案 2 :(得分:0)

如果数据每分钟都在下降,并且您只想在给定范围内(最后一小时或最后一天),则只需将行限制在范围内并选择1:

select top 1
       [Value], [Time]
  from [AbsoluteData]
 where [Sensor] = '5100'
   and cast(Time as date) = cast(dateadd(day, -1, getdate()) as date)
 order by Time desc;

(昨天最后一次)

或:

set rowcount 1;

select [Value], [Time]
  from [AbsoluteData]
 where [Sensor] = '5100'
   and cast(Time as date) = cast(dateadd(day, -1, getdate()) as date)
 order by Time desc;

set rowcount 0;