如何在MYSQL中为单个id计算同一列中不同的记录值

时间:2016-05-12 04:30:57

标签: mysql

我有一个类似

的mysql表

学生表

id|classid|name     |sectionid
--|-------|---------|-------
1 |1      |ashok    |1
2 |1      |viji     |2
3 |2      |sreekesh |1

班级表

id|name
--|----
1 |class1     
2 |class2

部分表

id|name
--|----
1 |A     
2 |B

家庭作业表

id|classid|activity   |sectionid
--|-------|-----------|---------
1 |1      |test       |1
2 |1      |assignment |2
3 |1      |test       |2
4 |1      |test       |2
5 |1      |assignment |2
6 |2      |assignment |1

我想把class1学生的测试活动计算为总测试和分配活动作为总的家庭作业。 我的预期结果如下:

student_name|class_name|total_test|total_assignment|section
------------|----------|----------|----------------|--------
ashok       |class1    |3         |2               |A
viji        |class1    |3         |2               |B

3 个答案:

答案 0 :(得分:2)

您可以尝试此操作(check at sqlfiddle)。

SELECT s.name AS student_name,
  c.name AS class_name,
  COUNT(IF(h.activity = "test", h.id, NULL)) AS total_test,
  COUNT(IF(h.activity = "assignment", h.id, NULL)) AS total_assignment
FROM student s
  JOIN class c ON s.classid = c.id
  JOIN homework h ON h.classid = c.id
WHERE c.id = 1 AND h.sectionid = 2
GROUP BY s.id, c.id

部分更新。

只有与学生的部分相同,才能计算作业?你可以通过这种方式实现它(fiddle):

SELECT s.name AS student_name,
  c.name AS class_name,
  COUNT(IF(h.activity = "test", h.id, NULL)) AS total_test,
  COUNT(IF(h.activity = "assignment", h.id, NULL)) AS total_assignment,
  sec.name AS section
FROM student s
  JOIN class c ON s.classid = c.id
  JOIN homework h ON h.classid = c.id AND h.sectionid = s.sectionid
  JOIN section sec ON sec.id = s.sectionid
GROUP BY s.id, c.id

答案 1 :(得分:0)

我会选择安德鲁回答,但下面是另一种获得确切结果的方法

select s.name as student_name, c.name as class_name,count(hw1.activity) as total_test,(select count(activity) from homework hw2
where hw2.classid=s.classid and hw2.classid=c.id and activity='assignment') as total_assignemnt
from homework hw1 join student s on hw1.classid=s.classid and hw1.activity='test' join class c on hw1.classid=c.id
group by s.name 

答案 2 :(得分:0)

尝试以下查询

   SELECT ST.STUDENTNAME, CT.CLASSNAME,
    COUNT(HW1.CLASSID) AS [TOTAL TESTS], COUNT(HW2.CLASSID) AS [TOTAL ASSIGNMENTS]    
     FROM STUDENT AS ST 
     LEFT OUTER JOIN CLASSTABLE CT ON CT.ID= ST.CLASSID
     LEFT OUTER JOIN HOMEWORK HW1 ON HW1.CLASSID = CT.ID AND HW1.ACTIVITY='TEST'
     LEFT OUTER JOIN HOMEWORK HW2 ON HW2.CLASSID = CT.ID AND HW1.ACTIVITY ='ASSIGNMENT'
     GROUP BY ST.STUDENTNAME