在SQL查询中,我们可能会有这样的需求,如下面的表
如果我们想统计一下,2班中,男生和女生的比例,那么可以怎么做呢,我们可以
SELECTS1.male AS 男,S2.female AS 女,S1.male / ( S1.male + S2.female ) AS result FROM( SELECT count( * ) AS male FROM test2 WHERE class = '2' AND sex = '男' ) S1,( SELECT count( * ) AS female FROM test2 WHERE class = '2' AND sex = '女' ) S2
结果:
这样,就查询出了2班中,男生所占比例。
换一个问题,如果我们想统计一下,1班和2班所有人中,喜欢赚钱的人所占的比例,我们可以
SELECTS1.zhuanqian AS 喜欢赚钱,S2.sumary AS 总人数,S1.zhuanqian / S2.sumary AS result FROM(SELECTcount( * ) AS zhuanqian FROMtest2 WHERE( class = '1' OR class = '2' ) AND LOCATE( '赚钱', fav ) ) S1,( SELECT count( * ) AS sumary FROM test2 WHERE class = '1' OR class = '2' ) S2
结果:
很明显,所有人都喜欢赚钱,没毛病。
如果觉得《MySQL统计两部分查询结果记录数量比值》对你有帮助,请点赞、收藏,并留下你的观点哦!