SQL 如何在 SUM 中使用 LAG

SQL How to use LAG inside SUM

我的 table(名称 EPM1):

TIMESTAMP INVERTER1POWER INVERTER2POWER POWERLIMIT
2021-09-30T17:19:42.309Z 100 400 0.8
2021-09-30T17:20:42.309Z 200 500 0.6
2021-09-30T17:21:42.309Z 300 600 0.7

我有这样的查询:

SELECT SUM(CASE WHEN (INVERTER1POWER+INVERTER2POWER) < (250000*POWERLIMIT) THEN INVERTER1POWER+INVERTER2POWER END) AS SUM1
  FROM EPM1
  WHERE TIMESTAMP >= TO_UTC_TIMESTAMP_TZ(:timefrom) AND TIMESTAMP <= TO_UTC_TIMESTAMP_TZ(:timeto)

这给了我输出:

SUM1
2100

我想要类似的单一值,但在计算中使用前一行的 POWERLIMIT - 在这部分 (250000*POWERLIMIT)。因此对于第一次迭代它将是 (100+400)*0 因为没有以前的值。然后 (200+500)*0.8 然后 (300+600)*0.6.

我尝试使用类似 LAG(POWERLIMIT, 1, 0) 的 LAG 函数,但无法在 SUM 中使用它。

使用嵌套子查询:

SELECT SUM(temp_value) AS sum2
FROM   (
  SELECT CASE
         WHEN INVERTER1POWER+INVERTER2POWER
              < 25000 * LAG(POWERLIMIT, 1, 0) OVER (ORDER BY timestamp)
         THEN INVERTER1POWER+INVERTER2POWER
         END AS temp_value
  FROM   epm1
)

其中,对于示例数据:

CREATE TABLE EPM1 (TIMESTAMP, INVERTER1POWER, INVERTER2POWER, POWERLIMIT) AS
SELECT TIMESTAMP '2021-09-30 17:19:42.309 UTC', 100, 400, 0.8 FROM DUAL UNION ALL
SELECT TIMESTAMP '2021-09-30 17:20:42.309 UTC', 200, 500, 0.6 FROM DUAL UNION ALL
SELECT TIMESTAMP '2021-09-30 17:21:42.309 UTC', 300, 600, 0.7 FROM DUAL

输出:

SUM2
1600

db<>fiddle here