Mysq查询总数、合格数及合格率

本文深入探讨了使用SQL进行数据统计的高级技巧,包括如何正确统计特定状态的数据,按日期分组统计并计算合格率,以及如何利用CASE语句优化查询效率。通过实际案例,读者可以学习到如何避免常见统计陷阱,提升数据处理能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
CREATE TABLE `new_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stat` int(11) DEFAULT '0',
`_time` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
*/

#stat=0代表无效
#stat=1代表成功
#stat=2代表失败

use lihcheng;
SELECT * FROM new_table;

#select count(stat=1) as allCount from new_table ; #不能正确统计stat=1,即统计的是总数

select count(stat=1 or null) as allCount from new_table ;#or null代表stat!=1则返回null,count对null不会做统计,所以统计正确
select count(stat=1 and _time='2019-04-20' or null) as allCount from new_table ;#统计stat=1并且时间是2019-04-20的记录

select _time,count(stat>=0 or null) as allCount,count(stat=1 or null) as okCount from new_table group by _time; #按日期统计总数和合格数
select _time,count(stat>=0 or null) as allCount,count(stat=1 or null) as okCount, (count(stat=1 or null)/count(stat>=0 or null) *100) as yeild from new_table group by _time; #按日期统计总数和合格数,并计算合格率
select _time,count(CASE WHEN stat>=0 THEN 1 ELSE NULL END) as allCount,count(CASE WHEN stat=1 THEN 1 ELSE NULL END) as okCount, (count(stat=1 or null)/count(stat>=0 or null) *100) as yeild from new_table group by _time; #按日期统计总数和合格数,并计算合格率

转载于:https://www.cnblogs.com/ITCheng2019/p/10755560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值