0

我有一个包含三列的学生表

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 组合的通过科目计数。对于失败和缺席的测试也是如此。

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

4

3 回答 3

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)
于 2013-03-01T14:14:47.323 回答
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);
于 2013-03-01T14:15:24.873 回答
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;
于 2013-03-01T14:18:29.770 回答