简体   繁体   English

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

[英]Group By clause Issue when using case statement

I am trying to sum up volumes across the year for every distinct sender and have the years as fields.我试图总结每个不同发件人全年的数量,并将年份作为字段。 I am using a case statement to do this.我正在使用 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

When i run this i get an error that asks me to group by month, Month is not one of the columns i am selecting, i am only using it in my condition... how do i solve this?当我运行这个时,我收到一个错误,要求我按月分组,月份不是我选择的列之一,我只在我的情况下使用它......我该如何解决这个问题?

I think you want conditional aggregation -- the case expression is an argument to the sum() :我认为你想要条件聚合—— 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

You got this error because your case statement is running row by row hence o/p for each row doesnt match the group of each row.您收到此错误是因为您的 case 语句逐行运行,因此每行的 o/p 与每行的组不匹配。 Try the below试试下面

   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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM