SQL group by和count对主题的成绩总计

时间:2014-09-19 14:35:15

标签: sql

我没有找到一个与我想要做的完全匹配的答案。

我不完全确定如何做到这一点非常诚实!

我有一张表,其中包括每个科目的学生所取得的成绩:

student course grades

我想要的是一张表格,显示每个科目的成绩分布,每个等级的总数:

student course grades

到目前为止,我的查询是:

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;

任何意见或建议都将不胜感激。

感谢。

2 个答案:

答案 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
  • 字符串常量由单引号而不是双引号分隔。单引号是ANSI标准,应该用于字符串和日期常量。
  • 这称为数据透视查询,有些数据库具有直接支持它们的语法。

答案 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;