I am trying to get my list of counts into a single row result set.
Consider this simple data set:
GRADES
=====================
ID NAME MIN MAX
1 A 91 100
2 B 81 90
3 C 71 80
=====================
Units
=====================
ID NAME
1 Unit 1
2 Unit 2
=====================
TESTS
=====================
ID UNIT_ID SCORE
1 1 80
2 1 92
3 1 95
4 1 94
5 2 92
6 2 85
7 2 76
8 2 73
======================
I want to get the result set to be something like this:
Unit_Name Grades Counts
Unit 1 A,B,C 3,1,0
Unit 2 A,B,C 2,1,1
Or even better, a JSON object:
Unit_Name Grade_Counts
Unit 1 {A: 3, B: 1, C: 0}
Unit 2 {A: 2, B: 1, C: 1}
I am easily able to create the grades and counts, but I end up with this, which doesn't match what I'm trying to achieve above.
UNIT_NAME Grade Count
Unit 1 A 3
Unit 1 B 1
Unit 1 C 0
Unit 2 A 2
Unit 2 B 1
Unit 2 C 1
UPDATE:
Here is the simple query I'm using, and I cannot use any of the GROUP_CONCAT
or the json_objectagg
function against the count field.
SELECT units.name as unit_name, grades.name as grade, count(grades.name) as count
FROM units
join tests on tests.unit_id = units.id
join grades on tests.score BETWEEN grades.min and grades.max
group by units.id, grades.name
order by units.id;