3

我有一个带有三个表的 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 但无法找出正确的。

任何人都可以帮忙吗?

4

1 回答 1

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;
于 2012-11-22T15:19:53.270 回答