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;
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.