SQL SELECT最接近15分钟的时间戳

时间:2013-01-03 02:07:06

标签: sql select timestamp subquery case

我想对每个15分钟时间值的最接近值执行SQL SELECT。例如:

00:15,
00:30,
00:45,
01:00,
01:15 etc...

基于时间戳(时间),如果已经设法将每个值舍入到最接近的15分钟,那么在使用以下标记的00秒内不是很完整,但我只想要最接近的值,例如。

SELECT dateadd(minute, -1 * datediff(minute, 0, 
    cast(convert(varchar(20),[time],100) as smalldatetime)) % 15, 
    dateadd(minute, datediff(minute, 0, [time]), 0)) as [TIMESTAMP],
    cast(convert(varchar(20),[time],100) as smalldatetime), [time], 
    tagname , value
FROM hdata
INNER JOIN rtdata
    ON hdata.tag_id = rtdata.id
WHERE tagname = 'M1_WH_004'
order by [TIMESTAMP] desc

(注意:我需要内部联接来提取标记名,因为它们不在hdata表中)

产生

example data

因此,对于每15分钟,我只想要最接近15分钟边界的值。对于上述数据,09:45和09:30的数据分别为09:45:15.383和09:30:17.463。

我是否需要子查询或案例陈述? 任何帮助将不胜感激!

除此之外,还有一个表格看起来像解决方案中的数据(每15分钟一次数据),子查询基于最后两个值执行计算,如下所示:

SELECT DD1.[TIME_STAMP] AS [TIME_STAMP], DD1.[kWh1] AS [kWh1], DD1.[kWh2] AS [kWh2], (DD1.[kWh1] + DD1.[kWh2]) AS [Total] FROM (SELECT a.ID
      ,a.TIME_STAMP
      ,(a.[1_M1_Wh] - (SELECT TOP 1 b.[1_M1_Wh] FROM TagCapture b WHERE b.TIME_STAMP = DATEADD(MINUTE, -15, a.TIME_STAMP))) * 0.04 AS kWh1
      ,(a.[1_M2_Wh] - (SELECT TOP 1 b.[1_M2_Wh] FROM TagCapture b WHERE b.TIME_STAMP = DATEADD(MINUTE, -15, a.TIME_STAMP))) * 0.04 AS kWh2
  FROM [TagCapture] a) DD1 

如何使用此查询中提供的解决方案?我对所有子查询都有些困惑。

即。所以基于t子查询定义的数据,取一个15分钟的计数值减去前一个并乘以得到所需的值,我将在每个FROM子句中插入t子查询?我似乎无法让它发挥作用。以上就是t查询将为'M1'和'M2'定义两个不同的标记名。

提前再次感谢!!

1 个答案:

答案 0 :(得分:1)

看起来您正在使用SQL Server。如果是这样,那么您可以使用row_number()来解决此问题。

select t.*
from (select t.*, row_number() over (partition by tagname, time15 order by time) as seqnum
      from (SELECT dateadd(minute, -1 * datediff(minute, 0, cast(convert(varchar(20),[time],100) as smalldatetime)) % 15, dateadd(minute, datediff(minute, 0, [time]), 0)) as [TIMESTAMP], cast(convert(varchar(20),[time],100) as smalldatetime) as time15,
                   [time], tagname , value
            FROM hdata INNER JOIN rtdata
                 ON hdata.tag_id = rtdata.id
            WHERE tagname = 'M1_WH_004'
          ) t
    ) t
where seqnum = 1