Group By子句使用case语句时的问题

时间:2019-10-29 16:20:04

标签: sql postgresql

我试图总结每个不同的发件人的全年交易量,并将年份作为字段。我正在使用一个case语句来做到这一点。

from benedict import benedict

d = benedict({'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}})

def traverse_item(dct, key, value):
   print('key: {} - value: {}'.format(key, value))

d.traverse(traverse_item)

当我运行此程序时,出现一个错误,要求我按月分组,月份不是我选择的列之一,我仅在我的情况下使用它...我该如何解决呢?

2 个答案:

答案 0 :(得分:1)

我认为您需要条件聚合-case表达式是sum()的参数:

select sender,
       sum(case when extract(month from (month)) = 1 then volume end) as January,
       sum(case when extract(month from (month)) = 2 then volume end) as February,
       sum(case when extract(month from (month)) = 3 then volume end) as March
from [lifetime_data]
group by 1

答案 1 :(得分:0)

您收到此错误,因为您的case语句逐行运行,因此每一行的o / p与每一行的组都不匹配。试试下面的

   Select sender, 
  extract(month from (month)), 
    SUM(Volume) from table group by
     sender, 
  extract(month from (month)) having
    extract(month from (month)) IN 
      (1,2,3)