我没有找到一个与我想要做的完全匹配的答案。
我不完全确定如何做到这一点非常诚实!
我有一张表,其中包括每个科目的学生所取得的成绩:
我想要的是一张表格,显示每个科目的成绩分布,每个等级的总数:
到目前为止,我的查询是:
SELECT subjectcode,
(SELECT COUNT(grade) FROM results WHERE grade = "A") as A,
(SELECT COUNT(grade) FROM results WHERE grade = "B") as B,
(SELECT COUNT(grade) FROM results WHERE grade = "C") as C,
(SELECT COUNT(grade) FROM results WHERE grade = "D") as D,
(SELECT COUNT(grade) FROM results WHERE grade = "E") as E
FROM results
GROUP BY grade
ORDER BY subjectcode ASC;
任何意见或建议都将不胜感激。
感谢。
答案 0 :(得分:2)
使用条件聚合,而不是多个子查询:
SELECT subjectcode,
SUM(CASE WHEN grade = 'A' THEN 1 END) as A,
SUM(CASE WHEN grade = 'B' THEN 1 END) as B,
SUM(CASE WHEN grade = 'C' THEN 1 END) as C,
SUM(CASE WHEN grade = 'D' THEN 1 END) as D,
SUM(CASE WHEN grade = 'E' THEN 1 END) as E
FROM results
GROUP BY subjectcode
ORDER BY subjectcode ASC;
注意:
group by
子句已修复。您在grade
中有group by
但尚未按subjectcode
排序,这没有任何意义。在大多数数据库中甚至都不允许这样做。else
上没有case
条款,因此不匹配产生NULL
。答案 1 :(得分:0)
declare @grades table(result_id int identity, upn int, grade varchar(2), subjectcode varchar(2))
insert into @grades (upn,grade,subjectcode) values
(1,'D','Ar'),
(1,'A','Bi'),
(1,'C','Ch'),
(2,'A*','Ar'),
(2,'B','Ch'),
(2,'A*','PE'),
(3,'C','Ar'),
(3,'C','Ph'),
(3,'A','Bi')
SELECT subjectcode,
ISNULL(SUM(CASE WHEN grade = 'A*' THEN 1 END),'') 'A*',
ISNULL(SUM(CASE WHEN grade = 'A' THEN 1 END),'') A,
ISNULL(SUM(CASE WHEN grade = 'B' THEN 1 END),'') B,
ISNULL(SUM(CASE WHEN grade = 'C' THEN 1 END),'') C,
ISNULL(SUM(CASE WHEN grade = 'D' THEN 1 END),'') D,
ISNULL(SUM(CASE WHEN grade = 'E' THEN 1 END),'') E,
ISNULL(SUM(CASE WHEN grade = 'F' THEN 1 END),'') F,
ISNULL(SUM(CASE WHEN grade = 'G' THEN 1 END),'') G,
ISNULL(SUM(CASE WHEN grade = 'U' THEN 1 END),'') U,
ISNULL(SUM(CASE WHEN grade = 'X' THEN 1 END),'') X
FROM @grades
GROUP BY subjectcode
ORDER BY subjectcode ASC;