繁体   English   中英

计算每n条记录SQL

[英]Calculate Every n record SQL

我有下表:

oDateTime                oValue
------------------------------------
2017-09:30 23:00:00      8
2017-09-30 23:15:00      7
2017-09-30 23:30:00      7
2017-09-30 23:45:00      7
2017-10-01 00:00:00      6
2017-10-01 00:15:00      5
2017-10-01 00:30:00      8
2017-10-01 00:45:00      7
2017-10-01 01:00:00      6
2017-10-01 01:15:00      9
2017-10-01 01:30:00      5
2017-10-01 01:45:00      6
2017-10-01 02:00:00      7

该表每15分钟将有一条记录。 我想每15分钟对这些记录SUMAverage一次。
因此,结果应为:

oDateTime                Sum_Value      Avg_Value
---------------------------------------------------
2017-10-01 00:00:00      35             7
2017-10-01 01:00:00      32             6.4
2017-10-01 02:00:00      33             6.6

2017-10-01 00:00:00SUM取自之前的5条记录,依此类推。
有谁知道如何做到这一点?

谢谢。

这是SQL Server 2008中的一种方法:

select t.oDateTime, tt.sum_value, tt.avg_value
from (select oDateTime
      from t
      where datepart(minute, oDateTime) = 0
     ) t outer apply
     (select sum(oValue) as sum_value, avg(oValue) as avg_Value
      from (select top 5 t2.*
            from t t2
            where t2.oDateTime <= t.oDateTime
            order by t2.oDateTime desc
           ) tt
     ) tt;

在SQL Server的最新版本中,可以将窗口函数用于此目的。

只需将表自身连接起来,并按主时间戳分组

您可以轻松调整以下内容,以包含所需的返回时间。 处理频率的变化,即不假定需要5行,因此,如果数据以5分钟为间隔进入,则进行处理。

select cast('2017-09-30 23:00:00' as datetime) t,8  o
into #a
union all
select '2017-09-30 23:15:00',7 union all
select '2017-09-30 23:30:00',7 union all
select '2017-09-30 23:45:00',7 union all
select '2017-10-01 00:00:00',6 union all
select '2017-10-01 00:15:00',5 union all
select '2017-10-01 00:30:00',8 union all
select '2017-10-01 00:45:00',7 union all
select '2017-10-01 01:00:00',6 union all
select '2017-10-01 01:15:00',9 union all
select '2017-10-01 01:30:00',5 union all
select '2017-10-01 01:45:00',6 union all
select '2017-10-01 02:00:00',7 

select x.t,sum(x2.o),avg(cast(x2.o as float))
from   #a x, #a x2
where  x2.t between dateadd(mi,-60,x.t) and x.t 
group by x.t

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM