我有一个包含金融交易的表,并且想要创建每天的运行总计。这是正确的方法吗?有更好的办法吗?它似乎有效,但我在 stackoverflow 上找不到这个特定的组合(
SUM ... OVER
与GROUP BY
),并且嵌套的SUM
需要额外的一双眼睛:
SELECT date,
SUM(SUM(amount)) over (PARTITION BY TRUE ORDER BY date) AS value
FROM transactions
GROUP BY date
ORDER BY date ASC
示例数据:
date amount
2024-11-01 00:00:00+00 - 1.9
2024-11-01 00:00:00+00 - 1.9
2024-11-02 00:00:00+00 - 1.9
2024-11-02 00:00:00+00 10
2024-11-05 00:00:00+00 3.9
2024-11-08 00:00:00+00 - 1.95
2024-11-13 00:00:00+00 - 10
2024-11-16 00:00:00+00 80
2024-11-18 00:00:00+00 85
2024-11-23 00:00:00+00 498.25
2024-11-27 00:00:00+00 -498.25
2024-11-30 00:00:00+00 -650
预期结果:
date amount
2024-11-01 00:00:00+00 - 3.8
2024-11-02 00:00:00+00 4.3
2024-11-05 00:00:00+00 8.2
2024-11-08 00:00:00+00 6.25
2024-11-13 00:00:00+00 - 3.75
2024-11-16 00:00:00+00 76.25
2024-11-18 00:00:00+00 161.25
2024-11-23 00:00:00+00 659.5
2024-11-27 00:00:00+00 161.25
2024-11-30 00:00:00+00 -488.75
您可以使用
DISTINCT ON
删除“重复”行:
SELECT
DISTINCT ON (trans_date)
trans_date,
SUM(amount) OVER(ORDER BY trans_date)
FROM transactions;
请参阅此 db<>fiddle 以及您的示例数据。