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

时间:2014-04-23 14:35:52

标签: sql sql-server count distinct multiple-columns

我正在尝试完成一个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分,因为有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      |

这可能比我想的要简单但是在那一刻我无法理解它。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

在按学校和学生对数据进行分组后,您需要通过PIVOT对每个主题数量的学生进行计算,以获得直方图“分档”:

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 here

我假设有限数量的主题,但您也可以使用dynamic sql

来推导列

答案 1 :(得分:1)

Group by应该解决这个问题,如下所示:

select SCHOOL, subject, count(*) as NUM_STUDENTS from records
group by STUDENT, SCHOOL;

答案 2 :(得分:1)

现在,我没有使用SQL Server而且我没有方便的SQL命令行,但你尝试过这样的事情:

SELECT SCHOOL, N, COUNT(STUDENT) 
FROM (SELECT SCHOOL, STUDENT, COUNT(DISTINCT SUBJECT) AS N 
FROM MY_TABLE GROUP BY SCHOOL, STUDENT) GROUP BY SCHOOL, N;