问题描述
开发过程中有时候我们需要对一些数据进行进行补行处理,通过代码实现的方式我就不多说了,接下来我给大家展示一下通过sql的实现方式。
#准备表
CREATE TABLE `test_student_count` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`school_code` varchar(255) DEFAULT NULL,
`course_type` varchar(255) DEFAULT NULL,
`student_count` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
#数据准备
INSERT INTO `test`.`test_student_count`(`id`, `school_code`, `course_type`, `student_count`) VALUES (1, '001', '1', '10');
INSERT INTO `test`.`test_student_count`(`id`, `school_code`, `course_type`, `student_count`) VALUES (2, '001', '3', '21');
INSERT INTO `test`.`test_student_count`(`id`, `school_code`, `course_type`, `student_count`) VALUES (3, '002', '3', '16');
数据展示:
理想结果:
你的结果:
如果course_type没有对应的记录,那么这一行的数据都没有
解决思路
1.先模拟出来应有行数的数据表t1
2.用真实数据表t2对模拟表t1进行左关联
3.真实数据表t2有值的展示真实数据,没有的话补0
具体实现
SELECT
basic.school_code,
basic.course_type,
IFNULL( tsc.student_count, 0 ) student_count
FROM
(
SELECT
*
FROM
( SELECT school_code FROM test_student_count GROUP BY school_code ) t1
CROSS JOIN ( SELECT 1 AS course_type, '物理' AS course_name UNION ALL SELECT 2, '化学' UNION ALL SELECT 3, '生物' ) t2
) basic
LEFT JOIN
test_student_count tsc ON basic.school_code = tsc.school_code
AND basic.course_type = tsc.course_type
ORDER BY
basic.school_code,
course_type;
执行结果: