gpt4 book ai didi

postgresql - 按组使用 case 语句运行总和

转载 作者:行者123 更新时间:2023-12-04 07:14:02 26 4
gpt4 key购买 nike

我想计算运行总和,但我的代码不起作用,有些想法为什么?

select id, color, time,  (sum(case when question = 1 then 1 else 0 end) OVER (PARTITION BY id ORDER BY time rows) + 
sum(case when suggestion='True' then 1 else 0 end) OVER (PARTITION BY id ORDER BY time) +
sum(case when proposal= 'True' then 1 else 0 end) OVER (PARTITION BY id ORDER BY time)) as s
from table
这是示例数据
id       color   time   question    suggestion    proposal 
1 pink 14:00 0 True False
1 red 15:00 0 False False
1 blue 13:00 0 False False
2 green 11:00 0 True False
2 orange 15:00 1 False False
结果:
id       color   time      s
1 pink 14:00 1
1 red 15:00 1
1 blue 13:00 0
2 green 11:00 1
2 orange 15:00 2

最佳答案

您需要使用 SUM()如果将所有 boolean 表达式转换为整数,则窗口函数仅一次:

SELECT id, color, time,
SUM((question = 1)::int + suggestion::int + proposal::int) OVER (PARTITION BY id ORDER BY time) s
FROM tablename
ORDER BY id, time;
demo .

关于postgresql - 按组使用 case 语句运行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68894085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com