SQL函式Group_concat用法

TayGo發表於2020-10-21

SQL函式Group_concat用法

參考自:https://blog.csdn.net/qq_35531549/article/details/90383022

Group_concat函式用於在group by分組之後,把分組隱藏的資訊顯示出來,預設用","分割。

首先有一張表:

在這裡插入圖片描述

1.現在需求就是根據age分組,分組後把每組的score都顯示出來,使用SQL:

SELECT d.age,GROUP_CONCAT(d.score)
from demo_1 d
where d.id is not null
group by d.age

結果:

在這裡插入圖片描述

2.預設的分隔符也可以替換,如替換成"–":

SELECT d.age,GROUP_CONCAT(d.score Separator '--')
from demo_1 d
where d.id is not null
group by d.age

結果:

在這裡插入圖片描述

3.還可以去重,在函式內加DISTINCT:

SELECT d.age,GROUP_CONCAT(DISTINCT d.score)
from demo_1 d
where d.id is not null
group by d.age

結果:

在這裡插入圖片描述

4.還可以排序,在函式內加order by:

SELECT d.age,GROUP_CONCAT(d.score order by d.score desc)
from demo_1 d
where d.id is not null
group by d.age

結果:
在這裡插入圖片描述

相關文章