SQLで複数行をカンマ区切り等で1行にまとめるgroup_concat
SQLで複数行から得られる結果を1行にまとめたい!なんて場合ありますよね。
行データをカンマ区切りデータの1列にしたい時だとか。
そんな夢をかなえます!
BEFORE
![](https://trios.pro/wp-content/uploads/2021/03/image-60.png)
AFTER
![](https://trios.pro/wp-content/uploads/2021/03/image-61.png)
使い方
基本
こんなtestというテーブルに対して実行してみます。
![](https://trios.pro/wp-content/uploads/2021/03/image-52.png)
まず一番基本の使い方。
複数行をカンマで区切って表示してみます。
select
group_concat(
col2 separator ',' -- カンマ区切り
)
from
test
;
縦に表示されてた行が横になりましたね!
![](https://trios.pro/wp-content/uploads/2021/03/image-53.png)
同じ値をまとめたい
同じ値は必要ない!という場合はdistinctを使えます。
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
)
from
test
;
1つずつにまとまりました!
![](https://trios.pro/wp-content/uploads/2021/03/image-54.png)
並び替え
order byも使える
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
order by col2 desc -- 並び替え
)
from
test
;
MySQLのバージョンの問題などで使えない場合はサブクエリ内でテーブルを作ってから
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
)
from
(
select
*
from
test
order by
col2 desc -- 並び替え
) as test2 -- サブクエリ
;
![](https://trios.pro/wp-content/uploads/2021/03/image-55.png)
条件
条件を指定したい場合はサブクエリ内でやっちゃいましょう
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
)
from
(
select
*
from
test
where
col2 != "A" -- 条件指定
order by
col2 desc -- 並び替え
) as test2 -- サブクエリ
;
![](https://trios.pro/wp-content/uploads/2021/03/image-56.png)
複数行表示
ちょっと応用編です。
いままでは全行を対象にして1行にまとめていましたが、
実践ではこのままでは使い物にならないでしょう。
何かの値ごとにグルーピングして連結するということが大半だと思います。
col2ごとにそれぞれマッチするものを連結するとこのようになります。
![](https://trios.pro/wp-content/uploads/2021/03/image-57.png)
やり方としてはgroup byの項目を追加するだけです。
select
col2
, group_concat(
distinct -- 同じ行は省略
col1 separator ',' -- カンマ区切り
)
from
test
group by
col2 -- このカラムごとに行をわける
![](https://trios.pro/wp-content/uploads/2021/03/image-58.png)
できました!
コメント