今天一个同事问我相关的问题,发现本身也不太清楚,特查看了解了下。sql
本文介绍下,用一条sql语句统计某一字段等于不一样值的个数,方法很独特,有须要的朋友参考下。spa
表t,数据: io
id type
001 1
001 0
002 1
001 0
002 0
001 1
001 0
002 0select
要求:
统计不一样id,type分别为0的,1的个数。sql语句
sql语句:
方法
复制代码代码示例:统计
select
id,sum(case when type=0 then 1 else 0 end) as 0,sum(case when type=1 then 1 else 0 end) as 1
from t
group by id数据
查询结果:
查询
id 0 1
001 3 2
002 2 1co
类似问题还有统计每一个班级男女生的个数