我有一个带有三个表的mysql数据库
学生 student_intervention 干预细节
我正在尝试制作一个显示所有学生的数据透视表视图,并为每种干预类型添加了列,为每个学生总结了不同类型的干预。
到目前为止我已经
了 SELECT t.`first_name`, t.`last_name`, t.`student_id`,
Count(IF(t.`intervention_details_id` = 1, 1, null)) AS Intervention1,
Count(IF(t.`intervention_details_id` = 0, 1, null)) AS Intervention2
FROM (
SELECT student.`student_id`, student.`first_name`,
student.`last_name`,
`student_intervention`.`intervention_details_id`
FROM student, student_intervention
WHERE student_intervention.student_id = student.`student_id`
) t
GROUP BY t.student_id
这有效,但它只显示有干预的学生的数据。我想要一份完整的学生名单,包括没有干预的学生。我想我需要一个JOIN但是找不到合适的人。
有人可以帮忙吗?
答案 0 :(得分:2)
使用LEFT JOIN
代替
SELECT a.`student_id`,
a.`first_name`,
a.`last_name`,
SUM(IF(COALESCE(b.`intervention_details_id`,0) = 1, 1, 0)) Intervention1,
SUM(IF(COALESCE(b.`intervention_details_id`,0) = 0, 1, 0)) Intervention2
FROM student a
LEFT JOIN student_intervention b
ON b.student_id = a.`student_id`
GROUP BY a.`student_id`, a.`first_name`, a.`last_name`
如果你想要准备好的陈述
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN COALESCE(b.intervention_details_id ,0) = ',
COALESCE(b.intervention_details_id ,0),
' THEN 1 ELSE 0 END) AS ',
COALESCE(b.intervention_details_id ,0)
)
) INTO @sql
FROM student a
LEFT JOIN student_intervention b
ON b.student_id = a.student_id;
SET @sql = CONCAT('SELECT a.student_id , a.first_name , a.last_name , ', @sql, '
FROM student a
LEFT JOIN student_intervention b
ON b.student_id = a.student_id
GROUP BY a.student_id , a.first_name , a.last_name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;