【问题标题】:running sum with case statements by group按组运行带有 case 语句的 sum
【发布时间】:2021-10-23 21:24:01
【问题描述】:

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

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        

【问题讨论】:

  • 发布示例数据和预期结果以阐明您想要什么。
  • @forpas 添加数据和结果
  • 建议和提案列的数据类型是什么?
  • @forpas 布尔值
  • 运行总和的行顺序是什么?只是时间,还是先 id 再时间?

标签: postgresql sum boolean window-functions cumulative-sum


【解决方案1】:

如果将所有布尔表达式转换为整数,则只需使用一次SUM() 窗口函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多