我有一个表,其中有ID,时间戳,一天的寄存器读取值,寄存器读取值就像运行总计从午夜的12.00开始到晚上的11.00结束。 问题是存在一些随机时间间隔,其中可能没有累积读数,我需要回填这些时间间隔,
下图给出了问题的快照,KWH_RDNG是两个累积间隔之间的差除以1000,但是第4列5.851实际上是3个缺失小时的累积以及第4小时的值。如果我简单地除以5.851 / 4并分发它就可以了。 挑战在于它们可能以随机间隔发生,并且对于不同的仪表(第一列)可能会有所不同。我正在使用SQL Server 2016。 请帮忙。!!
答案 0 :(得分:1)
这是一个空白和孤岛的问题。您需要使用后续值来标识NULL
值的组。一种方法是在每个值之后或之后使用非NULL
值的累积和。这定义了组。
然后,您需要计数和读数。因此,应该进行以下计算:
select t.*,
(max_kwh_rding / cnt) as new_kwh_rding
from (select t.*, count(*) over (partition by meter_serial, grp) as cnt,
max(kwh_rding) over (partition by meter_serial, grp) as max_kwh_rding
from (select t.*,
count(kwh_rding) over (partition by meter_serial order by read_utc desc rows between unbounded preceding and current row) as grp
from t
) t
) t
where cnt > 1;
您可以将其合并到update
中:
with toupdate as (
select t.*,
(max_kwh_rding / cnt) as new_kwh_rding
from (select t.*, count(*) over (partition by meter_serial, grp) as cnt,
max(kwh_rding) over (partition by meter_serial, grp) as max_kwh_rding
from (select t.*,
count(kwh_rding) over (partition by meter_serial order by read_utc desc rows between unbounded preceding and current row) as grp
from t
) t
) t
where cnt > 1
)
update toupdate
set kwh_rding = max_kwh_rding;