在同一列上多次计数并插入另一个表

时间:2013-03-01 14:12:24

标签: mysql sql pivot

我有一个有三列的学生表

1. Student Name
2. Class Name
3. Test result

学生需要进行多项测试,结果不同。我试图将数据放入另一个具有

的表中
1. Stundent Name+CLass Name ( Concatenated )
2. Pass (No of tests Passed)
3. Fail (No of tests failed)
4. Absent (No of tests Absent)

我用

select count(*)
from Student 
where Result in ('Passed')
group by StuName, ClassName;

获取每个stu + class组合的传递主题的计数。类似的失败和缺席测试。

我应该如何修改代码以插入表2?

3 个答案:

答案 0 :(得分:4)

MySQL支持内联 IF语句,

SELECT  CONCAT(StudentName, ' ', ClassName) Student_Class,
        SUM(test = 'PASSED') totalPass,
        SUM(test = 'Failed') totalFailed,
        SUM(test = 'Absent') totalAbsent
FROM    student
GROUP   BY CONCAT(StudentName, ' ', ClassName)

如果要插入上述查询的结果,请使用INSERT INTO..SELECT语句

INSERT  INTO tableNAME(col1, totalPass, totalFailed, totalAbsent)
SELECT  CONCAT(StudentName, ' ', ClassName) Student_Class,
        SUM(test = 'PASSED') totalPass,
        SUM(test = 'Failed') totalFailed,
        SUM(test = 'Absent') totalAbsent
FROM    student
GROUP   BY CONCAT(StudentName, ' ', ClassName)

答案 1 :(得分:2)

您可以使用带有CASE的聚合函数轻松转动数据:

select concat(StuName, ',', ClassName) StuNameClass,
  sum(case when result = 'Passed' then 1 else 0 end) Passed,
  sum(case when result = 'Fail' then 1 else 0 end) Fail,
  sum(case when result = 'Absent' then 1 else 0 end) Absent
from Student 
group by concat(StuName, ',', ClassName);

然后,如果要将数据插入到另一个表中:

insert into Table2 (StudentClassName, Passed, Fail, Absent)
select concat(StuName, ',', ClassName) StuNameClass,
  sum(case when result = 'Passed' then 1 else 0 end) Passed,
  sum(case when result = 'Fail' then 1 else 0 end) Fail,
  sum(case when result = 'Absent' then 1 else 0 end) Absent
from Student 
group by concat(StuName, ',', ClassName);

答案 2 :(得分:1)

INSERT INTO t (name_class, passed_count, failed_count, absent_count)
SELECT CONCAT(StuName, ' ', ClassName) AS name_class, 
       SUM(IF(Result='Passed', 1, 0)) AS passed_count, 
       SUM(IF(Result='Failed', 1, 0)) AS failed_count, 
       SUM(IF(Result='Absent', 1, 0)) AS absent_count
FROM Student
GROUP BY StuName, ClassName;