admin

SQL计数。当其他两列匹配时,如何计算表中有多少个不同的值?

sql

我正在尝试完成一个SQL查询,以显示一个学生记录了多少个GCSE。]

    *STUDENT         *SUBJECT                                     *SCHOOL
    ABB13778 |  English                                   | Social Care & Early Years
    ABB13778 |  Information and Communication Technology  | Social Care & Early Years
    ABB13778 |  Mathematics                               | Social Care & Early Years
    ABB13778 |  Media Studies                             | Social Care & Early Years

例如,由于有4个不同的科目分配给了学校和学生ID,因此该学生应获得4个计数。

我可以计算项目,但输出应该是学校和编号(见下文),而且我不确定玩具如何构成一个盒子

                               NUM OF STUDENT with each amount of GCSE
   SCHOOL                      1   2   3   4   5   6   7   8   9   10   11

   Social Care & Early Years | 5   1   2   7   0   1   13  15  8   4     2
   Built Environment         |
   Business & Computing      |

这可能比我想的要简单,但此刻我仍然无法解决。任何帮助将不胜感激。


阅读 174

收藏
2021-06-07

共1个答案

admin

在按学校和学生对数据进行分组之后,您需要对PIVOT每个学科数的学生人数进行遍历,以获取直方图“ bins”:

SELECT [School], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]
FROM
(
   SELECT School, Student, COUNT([Subject]) AS Subjects
   FROM Student_GCSE
   GROUP BY School, Student
) x
PIVOT
(
  COUNT(Student)
  FOR Subjects IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11])
) y;

SqlFiddle在这里

2021-06-07