【问题标题】:SQL query for backfilling register read values回填寄存器读取值的 SQL 查询
【发布时间】:2018-07-16 19:54:50
【问题描述】:

我有一张表,其中包含一天的 ID、时间戳、寄存器读取,寄存器读取就像运行总计从午夜 12.00 开始到晚上 11.00 结束。 问题是有一些随机时间间隔可能不存在累积读取,我需要回填那些,

下图给出了问题的快照,KWH_RDNG 是两个累积间隔之间的差除以 1000,但第 4 列 5.851 实际上是 3 个缺失小时与第 4 小时值的累积。如果我简单地划分 5.851/4 并分配它就可以了。 挑战在于它们可以随机发生,并且对于不同的仪表(第一列)可能会有所不同。我正在使用 SQL Server 2016。 请帮忙。!!

【问题讨论】:

  • 样本输入/输出?
  • 您是说要更新表并用其他值替换 0 和 NULL 吗?
  • @RavitejaVutukuri 上面的表格截图是一个示例输入。我只需要一个使用该表的选择查询,它可以回填这些零并将它们替换为立即值 5.851 /(零的数量)..(如 case 语句或其他东西)。
  • @TabAlleman 是的,我想要一个选择查询,它可以用 5.851 值的平均值替换 0 或 NULL。

标签: sql sql-server sql-server-2016


【解决方案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;

【讨论】:

  • 谢谢你,我会试试这个,让你知道。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2021-04-08
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
相关资源
最近更新 更多