[英]MySQL multiple count on the same column and insert the result to another table
[英]Multiple count on same column and insert into another table
我有一個學生表,其中有三列
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組合通過的科目的計數。 對於失敗和不存在的測試也是如此。
我應該如何修改代碼以插入表二中?
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)
您可以使用帶有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);
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.