简体   繁体   English

使用 postgresql 的 GROUP BY CASE 语句

[英]GROUP BY CASE statement with postgresql

I am trying to group by the CASE statement with postgresql, but i'm having this error "aggregate functions are not allowed in GROUP BY"我正在尝试使用 postgresql 通过 CASE 语句进行分组,但出现此错误“GROUP BY 中不允许使用聚合函数”

with zones as (select school, region, dt from district where dt between '1-jan-2021' and '31-jan-2021')
select c.region, to_char(a.dt, 'yyyy-mm') mth,
case when sum(a.payment)=0 then '0' else '1' end as seg,
sum(a.records)  records1,
sum(a.amount)  payment
from budget a   
left join zones c on (a.school = c.school and a.dt = c.dt)
where a.dt between '1-jan-2021' and '31-jan-2021'
group by   c.region, to_char(a.dt, 'yyyy-mm'), seg
order by c.site, to_char(a.dt, 'yyyy-mm'), seg;

thank you in advance先感谢您

The result of a group by can only be the expressions with attributes in the group (and attributes that are functionally dependent on the attributes in the group by) and aggregation functions (the parms to these functions can be any attribute). group by 的结果只能是具有 group 中属性的表达式(以及在功能上依赖于 group by 中的属性的属性)和聚合函数(这些函数的参数可以是任何属性)。 I suspect you can rewrite your query such that the final function is the sum (move the case inside the sum).我怀疑你可以重写你的查询,这样最终的函数就是总和(在总和中移动案例)。 But...但...

Since the "case" is in the final projection, you can do first do the the group by, then do another projection.由于“case”是在最后的投影中,你可以先做 group by,然后再做一次投影。

Do this (make sure you give names to each attribute that is computed with a sum, such as sumpayment):执行此操作(确保为使用总和计算的每个属性指定名称,例如 sumpayment):

WITH t as (-- original query with case removed
    SELECT ..., sum(a.payment) as sumpayment, 
     ...)
select ..., case when sumpayment=0 then '0' else '1' end as seg, 
   ... -- any other attribute
from T

that should do it应该这样做

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

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