SQL Count. How can I count how many distinct values are in a table when an other two columns are matching?

China☆狼群 提交于 2019-12-11 02:04:59

问题


I am trying to complete an sql query to show how many GCSEs a student has on record.]

    *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

For example this student should recieve a count of 4 as there is 4 distinct subjects assigned to the school and student ID.

I can count the items but the output should be by school and number(see below), and I am not sure how toy form a case to create this

                               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      |

This is probably simpler than I am thinking but at the minute I cant get my head around it. Any help would be greatly appreciated.


回答1:


After grouping the data by school and student, you need to then run it through a PIVOT on the count of Students with each number of subjects, to get the histogram '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 here

I've assumed a finite number of subjects, but you can derive the columns as well using dynamic sql




回答2:


Group by should solve this, Something like following:

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



回答3:


Now, I don't use SQL Server and I don't have a SQL command line handy, but have you tried something like this:

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;


来源:https://stackoverflow.com/questions/23247574/sql-count-how-can-i-count-how-many-distinct-values-are-in-a-table-when-an-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!