简体   繁体   中英

Multiple count on same column and insert into another table

I have a student table that has three columns

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

A student takes more than one tests with different results. I am trying to get the data into another table that has

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

I use

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

to get the count of passed subject for each stu+class combination. Similarly for failed and absent tests.

How should I modify the code to make an insert into the Table two??

MySQL supports inline IF statement,

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)

and when you want to insert the result from the query above, use INSERT INTO..SELECT statement,

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)

You can easily pivot the data using an aggregate function with a 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);

Then if you want to insert the data into your other table:

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);
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM