【发布时间】:2018-12-07 19:46:09
【问题描述】:
这是我的方法:
select distinct (invoice_no) as no,sum(total),
sum(case when department_id=2 then total end) as a2,
sum(case when department_id=3 then total end) as a3,
sum(case when department_id=4 then total end) as a4,
sum(case when department_id=5 then total end) as a5,
sum(case when department_id=6 then total end) as a6
from article_sale
where invoice_date = '2018-10-01' group by no order by no ASC
查询返回如下输出:
no sum a2 a3 a4 a5 a6
68630 690 NULL 75 404 NULL 210.8
68631 0 NULL NULL NULL NULL NULL
68632 132 NULL 45 87 NULL NULL
68633 75 NULL 75 NULL NULL NULL
68634 523 NULL 130 NULL NULL 392.55
68635 0 NULL NULL NULL NULL NULL
68636 310 NULL NULL 218 NULL 91.91
68637 273 NULL NULL NULL NULL 273.24
68638 0 NULL NULL NULL NULL NULL
我只想获取a6 为NOT NULL 的行。其他行应被过滤。
期望的输出:
no sum a2 a3 a4 a5 a6
68630 690 NULL 75 404 NULL 210.8
68634 523 NULL 130 NULL NULL 392.55
68636 310 NULL NULL 218 NULL 91.91
68637 273 NULL NULL NULL NULL 273.24
如何最好地实现这一目标?
【问题讨论】:
-
只要使用
having--having sum(case when department_id=6 then total end) is not null...
标签: sql postgresql aggregate having-clause