【问题标题】:Group By clause Issue when using case statement使用 case 语句时的 Group By 子句问题
【发布时间】:2019-10-29 16:20:04
【问题描述】:

我正在尝试为每个不同的发件人总结一年中的数量,并将年份作为字段。我正在使用 case 语句来执行此操作。

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

当我运行它时,我收到一个错误,要求我按月分组,月份不是我选择的列之一,我只是在我的情况下使用它......我该如何解决这个问题?

【问题讨论】:

    标签: sql postgresql


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      您收到此错误是因为您的 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) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        • 2019-02-16
        相关资源
        最近更新 更多