簡體   English   中英

如何在MYSQL中為單個ID計算同一列中記錄的不同值

[英]How to count different values of records in same column for single id in 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

我想將第1類學生的考試活動計為總考試,將作業分配為總作業。 我的預期結果是:

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

您可以嘗試此操作( 在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

更新各節。

僅當作業與學生相同時才算作業嗎? 您可以通過以下方式( 小提琴 )來實現:

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

我將回答安德魯,但下面是您想要獲得准確結果的另一種方法

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 

嘗試以下查詢

   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM