我有以下表格:
create table test
(
cola integer
)
有些数据:
cola
-------
0
1
0
2
0
3
0
4
0
5
此处我需要在count
中cola
个{0}个呈现数,并且还想要将大于0的其他值的数量相加,例如sum(1,2,3,4,5)
。
我的不好尝试:
select count(cola) as zeros ,sum(cola) as others
from test
where cola = 0 and cola > 0;
答案 0 :(得分:2)
您想要条件聚合:
select sum(case when cola = 0 then 1 else 0 end) as zeros,
sum(case when cola > 0 then cola else 0 end) as others
from test;
严格来说,假设值永远不会为负值,则不需要第二个条件:
select sum(case when cola = 0 then 1 else 0 end) as zeros,
sum(cola) as others
from test;
答案 1 :(得分:0)
此查询将计算可乐中零值的数量,以及大于0的其他值的总数,如sum(1,2,3,4,5)
<强>答案:强>
select
count (case when cola=0 then cola end) as Zeros,
sum (case when cola>0 then cola end) as otherthanzeroes
from test;