[英]Mysql - concat multiple rows into single row, including counts
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:或者更好,一个 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.这是我正在使用的简单查询,我不能对计数字段使用任何
GROUP_CONCAT
或json_objectagg
function。
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;
Try:尝试:
select unit_name,group_concat(grade) as Grades ,group_concat(nr_count) as Counts
from (
SELECT u.name as unit_name,
g.name as grade,
count(g.name) as nr_count
FROM units u
join tests t on t.unit_id = u.id
join grades g on t.score BETWEEN g.`min` and g.`max`
group by u.id, g.name,u.name
) as t1
group by t1.unit_name ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.