【SQL实战】一条SQL统计全国各地疫情分布情况
-- 疫情表,三个字段:城市/地区 省份 当前确诊人数
DROP TABLE IF EXISTS yiqing;
CREATE TABLE `datacenter`.`yiqing`(
`city` VARCHAR(32) COMMENT '城市/地区',
`province` VARCHAR(32) COMMENT '省份',
`current` INT COMMENT '当前确认人数'
)
COMMENT='疫情信息表';
INSERT INTO yiqing
SELECT '津南区', '天津', 217 UNION ALL
SELECT '安阳', '陕西', 110 UNION ALL
SELECT '西安', '陕西', 1385 UNION ALL
SELECT '咸阳', '河南', 10 UNION ALL
SELECT '郑州', '河南', 138 UNION ALL
SELECT '南阳', '河南', 95 UNION ALL
SELECT '呼伦贝尔', '内蒙古', 5 UNION ALL
SELECT '宁波', '浙江', 55 UNION ALL
SELECT '开封', '河南', 5 UNION ALL
SELECT '金华', '浙江', 3 UNION ALL
SELECT '防城港', '广西', 2 UNION ALL
SELECT '中山', '广东', 51 UNION ALL
SELECT '大连', '辽宁', 3 ;
SELECT * FROM yiqing ORDER BY 2,1;
-- §§§【统计全国疫情分布情况 结果列:省份、严重程度级别、累计确诊人数】
SELECT province AS '省份'
, CASE WHEN SUM(current)>=100 THEN 'Level1' WHEN SUM(current)<100 AND SUM(current)>=50 THEN 'Level2' ELSE 'Levy3' END AS '严重程度'
, SUM(current) AS '累计确认人数'
FROM yiqing
GROUP BY province
ORDER BY 3 DESC;
-- §§§【统计各省份疫情分布情况 结果列:省份、疫情风险等级、城市地区数、当前确诊数。例如:河南省有3个高风险城市,确诊人数总计300人】
SELECT province AS '省份'
, CASE WHEN current>=100 THEN '高'
WHEN current>=50 AND current<100 THEN '中'
ELSE '低' END AS '疫情风险等级'
, COUNT(1) AS '城市地区数'
, SUM(current) AS '当前确诊数'
FROM yiqing
GROUP BY province, CASE WHEN current>=100 THEN '高'
WHEN current>=50 AND current<100 THEN '中'
ELSE '低' END
ORDER BY 1, CASE 疫情风险等级 WHEN '高' THEN 1 WHEN '中' THEN 2 ELSE 3 END;
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/p/15797158.html