SQLで複数行をカンマ区切り等で1行にまとめるgroup_concat
SQLで複数行から得られる結果を1行にまとめたい!なんて場合ありますよね。
行データをカンマ区切りデータの1列にしたい時だとか。
そんな夢をかなえます!
BEFORE

AFTER

使い方
基本
こんなtestというテーブルに対して実行してみます。

まず一番基本の使い方。
複数行をカンマで区切って表示してみます。
select
group_concat(
col2 separator ',' -- カンマ区切り
)
from
test
;
縦に表示されてた行が横になりましたね!

同じ値をまとめたい
同じ値は必要ない!という場合はdistinctを使えます。
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
)
from
test
;
1つずつにまとまりました!

並び替え
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 -- サブクエリ
;

条件
条件を指定したい場合はサブクエリ内でやっちゃいましょう
select
group_concat(
distinct -- 同じ行は省略
col2 separator ',' -- カンマ区切り
)
from
(
select
*
from
test
where
col2 != "A" -- 条件指定
order by
col2 desc -- 並び替え
) as test2 -- サブクエリ
;

複数行表示
ちょっと応用編です。
いままでは全行を対象にして1行にまとめていましたが、
実践ではこのままでは使い物にならないでしょう。
何かの値ごとにグルーピングして連結するということが大半だと思います。
col2ごとにそれぞれマッチするものを連結するとこのようになります。

やり方としてはgroup byの項目を追加するだけです。
select
col2
, group_concat(
distinct -- 同じ行は省略
col1 separator ',' -- カンマ区切り
)
from
test
group by
col2 -- このカラムごとに行をわける

できました!
コメント