本文介绍下,用一条sql语句统计某一字段等于不同值的个数,方法很独特,有需要的朋友参考下。
表t,数据:
id type
001 1
001 0
002 1
001 0
002 0
001 1
001 0
002 0
001 1
001 0
002 1
001 0
002 0
001 1
001 0
002 0
要求:
统计不同id,type分别为0的,1的个数。
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,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 1
001 3 2
002 2 1
本文出处参考:http://www.jbxue.com/db/11867.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步