Say I have a relation grades
about students' grades like this:
| ID | semester | Year | course_id | grade |
|------+----------+------+-----------+-------+
| 1018 | Fall | 2002 | 272 | A+ |
| 107 | Fall | 2002 | 274 | B |
| 111 | Fall | 2002 | 123 | C |
/* a lot of data here */
|------+----------+------+-----------+-------+------------|
I wanna group by course_id
and count its grades like this:
| course_id | semester | year | A+ | A- | B+ | B- | C+ | D+ | D- | else | sum |
| 1 | Fall | 2009 | 11 | 8 | 10 | 1 | 1 | 1 | 1 | 1 | 34 |
| 2 | Fall | 2009 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 8 |
I already figured out one solution but seems not satisfying to me:
/* use sum function */
select course_id, semester, year,
sum(if(grade = 'A+', 1, 0)) as 'A+',
sum(if(grade = 'A-', 1, 0)) as 'A-',
/* multiple lines */
from grades
group by course_id, semester, year;
I wonder if there is a more built-in way to make it, because my above solution is kinda of tricky and not general.
Can anyone offer better idea?
p.s.: yes it's a school assignment, and I want to seek more solutions:) It will be appreciated if give me more hints.