我有一张桌子: -
id value
1 1
1 2
1 1
1 4
2 1
2 3
2 2
3 1
4 2
我想得到id和它们各自的计数值= 1,即对于上表,输出应该如下: -
id count
1 2
2 1
3 1
4 0
因为,id = 1有2个条目1,id = 2有1个条目1,类似id 3有1个条目,id 4有0个条目。
我使用以下阙获得以下输出: -
select id,count(value)
from table
where value=1
group by id
order by count(value);
id count
1 2
2 1
3 1
我也想获得4, 0
条目。我怎么能这样做?
答案 0 :(得分:6)
试试这个
select id,sum(case when value ='1' then 1 else 0 end) as val
from table
group by id
order by id;
答案 1 :(得分:1)
您尝试此Sql查询
select id,COUNT(CASE WHEN value = '1' THEN 1 END) count
from tablename
group by id;
答案 2 :(得分:0)
删除行id = 4
的where子句尝试以下:
select id,sum(case when value = 1 then 1 else 0 end) as count
from table
group by id
order by sum(case when value = 1 then 1 else 0 end);