■ はじめに
小ネタ。 RedshiftのLISTAGG 関数を調べている際に PostgreSQLのstring_agg が見つかったので メモっておく
目次
【1】string_agg 補足:Redshift / LISTAGG 【2】構文 【3】サンプル 例1:Hello world
【1】string_agg
* グルーピングした要素を指定された区切り文字で 結合表示する
補足:他のDBに関して
* SQL Server でも使えるみたい
補足:Redshift / LISTAGG
https://docs.aws.amazon.com/ja_jp/redshift/latest/dg/r_LISTAGG.html
より抜粋 ~~~~~~ クエリの各グループについて、LISTAGG 集計関数は、 ORDER BY 式に従ってそのグループの行をソートしてから、 それらの値を 1 つの文字列に連結します ~~~~~~ select listagg(sellerid, ', ') within group (order by sellerid) from sales where eventid = 4337; listagg -------------------------------- 380, 380, 1178, 1178, 1178, ... <= カンマ区切りで出力される
【2】構文
string_agg(expression, delimiter) # (text, text)または(bytea, bytea)
https://www.postgresql.jp/docs/9.2/functions-aggregate.html
【3】サンプル
例1:Hello world
SELECT code, string_agg(val,'! ' ORDER BY val) FROM ( SELECT '1', 'Hello' UNION SELECT '1', 'World' UNION SELECT '2', 'Hi' UNION SELECT '2', 'How are you?' ) AS sapmple(code, val) GROUP BY code;
出力結果
code,string_agg 1,Hello! World 2,Hi! How are you?
参考文献
http://tomofumi.blog.jp/archives/7990552.html
https://workmemo.techblog.jp/archives/33958716.html
https://qiita.com/anqooqie/items/ed4e1e29e70fba040673
関連記事
文字列関数 ~ split_part ~
https://dk521123.hatenablog.com/entry/2021/09/07/000000