0

I have a table (stu_grades) that stores student data and their grades at the centers they attended

I want to find out how many times for e.g. each student in that table got 'A' and then 'B' etc at any center

stu_grades

 stu_ID|grade1|grade2|Grade3|center
    1        A      A     C    1
    2        B      B     B    2
    3        C      C     A    1
    1        C      A     C    2

the same student could occur more than once in the table with the same grades or even a different grade, same or different center

I especially want to check where the grade has appeared more than 3 or more times and how many centeres they exist in

So the final output should be like:

Stu_ID|Grade|Count|centercount
1       A      3       2 (As they accquired 'A' from 2 centres)
1       C      3       2 
2       B      3       1 (As they only exist in 1 centre)
3       C      2       1 
3       A      1       1
healthiq
  • 25
  • 4
  • If you unpivot the data this would be a simple aggregation. Is the data stored in this pivoted fashion somewhere? or perhaps use the Unnest function described in this solution: http://stackoverflow.com/questions/1128737/unpivot-and-postgresql – xQbert Nov 18 '16 at 15:39
  • @xQbert can you help me understand these functions.. how do i make them relevant to my scenario – healthiq Nov 18 '16 at 15:45
  • I have edited the question slightly so any help is appreciated – healthiq Nov 30 '16 at 15:17

2 Answers2

1

This is one approach using union all to unpivot the different grades into one column and then doing an aggregation.

select stu_id,grade,count(*) cnt 
from (
select stu_id,grade_1 grade from stu_grades
union all
select stu_id,grade_2 grade from stu_grades
union all
select stu_id,grade_3 grade from stu_grades
) t
group by stu_id,grade
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
0

This should satisfy your requirement:

SELECT [Stud_ID], Grade, count(*) as GradeCount FROM
  (SELECT [Stud_ID],Grade1 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade2 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade3 as Grade from [Stud_Details]) AS T
   GROUP BY T.[Stud_ID],T.Grade
   ORDER BY T.[Stud_ID]

UPDATE:

You can use HAVING after GROUP BY to get gradeCount which are greater than 3.

SELECT [Stud_ID], Grade, count(*) as GrdCountStud FROM
  (SELECT [Stud_ID],Grade1 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade2 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade3 as Grade from [Stud_Details]) AS T
   GROUP BY T.[Stud_ID],T.Grade
     HAVING COUNT(*) > 3   
   ORDER BY T.[Stud_ID]
Kumar_Vikas
  • 837
  • 7
  • 16