1

我想为最接近每个 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 表中)

产生:

示例数据

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

我需要子查询或案例语句吗?任何帮助将不胜感激!

除此之外,a 已经有一个看起来像解决方案中的数据(每 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”定义两个不同标记名的地方。

再次提前感谢!

4

1 回答 1

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
于 2013-01-03T02:25:22.137 回答