mysql统计分组求和

mysql统计分组求和

1、由于工作需要对数据进行一个分组展示汇总处理,之前的处理情况如下:
SELECT
a.qxmc as ‘区县’,
count() as ‘下发数’,
SUM(b.sflxs is not null) as ‘核查数’,
SUM(b.sflxs is not null)/count(
) as ‘完成率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘查实数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1)/SUM(b.sflxs is not null) as ‘查实率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null) as ‘管控数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null)/SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘管控率’
FROM
t_jcxx a,t_hcryxx b where a.id=b.jcxxid
GROUP BY
a.qxmc
在这里插入图片描述
然后通过复制到Excel进行求和汇总处理,由于本人比较懒,所以想找一个直接出汇总的方法,想要的效果图如下:在这里插入图片描述
百度找了很多很多用例,基本没有找到相符合业务场景的sql,后面请教了一个大佬,通过拼接的方式弄出来了:SELECT
a.qxmc as ‘区县’,
count() as ‘下发数’,
SUM(b.sflxs is not null) as ‘核查数’,
SUM(b.sflxs is not null)/count(
) as ‘完成率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘查实数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1)/SUM(b.sflxs is not null) as ‘查实率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null) as ‘管控数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null)/SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘管控率’
FROM
t_jcxx a,t_hcryxx b where a.id=b.jcxxid
GROUP BY
a.qxmc
union ALL
select ‘汇总’,sum(a.xfs),sum(a.hcs),sum(a.wcs)/10,sum(a.css),sum(a.csl),sum(a.gks),sum(a.gkl)/10 from (
SELECT
a.qxmc as ‘区县’,
count() as xfs,
SUM(b.sflxs is not null) as hcs,
SUM(b.sflxs is not null)/count(
) as wcs,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as css,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1)/SUM(b.sflxs is not null) as csl,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null) as gks,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null)/SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as gkl
FROM
t_jcxx a,t_hcryxx b where a.id=b.jcxxid
GROUP BY
a.qxmc
) a
执行结果如下:
在这里插入图片描述
但是这个sql太冗余了,很不喜欢,想对它进行优化,最后找了很久很久,终于让我找到了这个宝藏sql函数:COALESCE。说实话这个函数见都没见过,之前问了挺多人,他们的经验都是分组之后不能直接汇总求和了,最后竟然被这一个小小的函数解决了,果然只要想得到,就一定能找到方法,我们言归正传,优化后的sql为:
SELECT
COALESCE(a.qxmc,‘汇总’) as ‘区县’,
count() as ‘下发数’,
SUM(b.sflxs is not null) as ‘核查数’,
SUM(b.sflxs is not null)/count(
) as ‘完成率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘查实数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1)/SUM(b.sflxs is not null) as ‘查实率’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null) as ‘管控数’,
SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1 and b.gkcs is not null)/SUM(b.sflxs=1 and b.sfchbl=1 and b.szdq=1) as ‘管控率’
FROM
t_jcxx a,t_hcryxx b where a.id=b.jcxxid
GROUP BY
a.qxmc WITH ROLLUP

我们来看一下运行结果:
在这里插入图片描述
完美契合,是我想要的结果。由于这么罕见的sql函数大家可能也跟我一样没有见过,所以特地发出来给大家安利一下!!!
在这里插入图片描述
觉得有用可以意思一下。

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值