一条sql查询出多个统计结果
统计一张表中不同类型的统计数量
例如,该表中有个type字段(值有0,1....),然后统计不同值下的总数
SELECT
COUNT(CASE WHEN `type`=0 OR `type`=1 THEN 1 ELSE NULL END) allTypeCount,
COUNT(CASE WHEN `type`=0 THEN 1 ELSE NULL END) zerotTypeCount,
COUNT(CASE WHEN `type`=1 THEN 1 ELSE NULL END) oneTypeCount
FROM `book_detail`
select
sum(case month(start_time) when '1' then 1 else 0 end) as 一月份,
sum(case month(start_time) when '2' then 1 else 0 end) as 二月份,
sum(case month(start_time) when '3' then 1 else 0 end) as 三月份,
sum(case month(start_time) when '4' then 1 else 0 end) as 四月份,
sum(case month(start_time) when '5' then 1 else 0 end) as 五月份,
sum(case month(start_time) when '6' then 1 else 0 end) as 六月份,
sum(case month(start_time) when '7' then 1 else 0 end) as 七月份,
sum(case month(start_time) when '8' then 1 else 0 end) as 八月份,
sum(case month(start_time) when '9' then 1 else 0 end) as 九月份,
sum(case month(start_time) when '10' then 1 else 0 end) as 十月份,
sum(case month(start_time) when '11' then 1 else 0 end) as 十一月份,
sum(case month(start_time) when '12' then 1 else 0 end) as 十二月
,2023 AS '年份'
from
pro_project WHERE YEAR(start_time) = 2023
两种查法 :
1.case when 赋值取count,赋值 1或 null
count(1) as zs,
count(case when vwym.yw_state = '办理中' then 1 ELSE NULL end) blz,
count(case when vwym.yw_state = '已办结' then 1 ELSE NULL end) ybj
2.case when 赋值 取和, 赋值1 或0
count(1) as zs,
ifnull(SUM(if(vwym.yw_state = '办理中' , 1, 0)) ,0) blz,
ifnull(SUM(if(vwym.yw_state = '已办结' , 1, 0)) ,0) ybj
择善人而交,择善书而读,择善言而听,择善行而从。