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

StackOverflow https://stackoverflow.com/questions/23247574

문제

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.

도움이 되었습니까?

해결책

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

다른 팁

Group by should solve this, Something like following:

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

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top