关于分组统计
select
sum(case when salary>9999 and age>35 then 1 else 0 end) AS ‘第一组’ ,
sum(case when salary>9999 and age<35 then 1 else 0 end) AS ‘第二组’ ,
sum(case when salary<9999 and age>35 then 1 else 0 end) AS ‘第三组’
from db_job.tb_emp ;
这里用到了sum,case-when-then-else-end;我个人的看法如果要统计四组数据,那么这个sql对全量数据做了四次查询;下面是优化后的:
select SUM(t.type='A') AS ‘第一组’ ,SUM(t.type='B') AS ‘第二组’,SUM(t.type='C') AS ‘第三组’
FROM ( SELECT case when salary>9999 and age>35 then 'A'
else( case when salary>9999 and age<35 then 'B'
else( case when salary<9999 and age>35 then 'C' else 'other'
END)
END)
END as 'type' from b_job.tb_emp
) t;