簡體   English   中英

Mysql - 將多行連接成單行,包括計數

[英]Mysql - concat multiple rows into single row, including counts

我正在嘗試將我的計數列表放入單行結果集中。

考慮這個簡單的數據集:

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
======================

我想讓結果集是這樣的:

Unit_Name   Grades    Counts
Unit 1      A,B,C     3,1,0
Unit 2      A,B,C     2,1,1

或者更好,一個 JSON object:

Unit_Name   Grade_Counts
Unit 1      {A: 3, B: 1, C: 0}
Unit 2      {A: 2, B: 1, C: 1}

我很容易就能創建成績和計數,但我最終得到了這個,這與我在上面想要實現的目標不符。

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

更新:

這是我正在使用的簡單查詢,我不能對計數字段使用任何GROUP_CONCATjson_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;

嘗試:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM