LISTAGG 関数
クエリの各グループについて、LISTAGG 集計関数は、ORDER BY 式に従ってそのグループの行をソートしてから、それらの値を 1 つの文字列に連結します。
LISTAGG はコンピューティングノード専用の関数です。クエリがユーザー定義のテーブルまたは Amazon Redshift システムテーブルを参照しない場合、関数がエラーを返します。
構文
LISTAGG( [DISTINCT] aggregate_expression [, 'delimiter' ] ) [ WITHIN GROUP (ORDER BY order_list) ]
引数
- DISTINCT
-
(オプション) 連結する前に、指定された式から重複した値を削除する句。末尾のスペースは無視されるので、
'a'
と'a '
という文字列は重複として扱われます。LISTAGG は、発生した最初の値を使用します。詳細については、「末尾の空白の重要性」を参照してください。 - aggregate_expression
-
集計する値を返す任意の有効な式 (列名など)。NULL 値および空の文字列は無視されます。
- delimiter
-
(オプション) 連結された値を区切る文字列定数。デフォルトは NULL です。
- WITHIN GROUP (ORDER BY order_list)
-
(オプション) 集計値のソート順を指定する句。
戻り値
VARCHAR(MAX). 結果セットが最大 VARCHAR サイズ (64K - 1、または 65535) より大きい場合、LISTAGG は以下のエラーを返します。
Invalid operation: Result size exceeds LISTAGG limit
使用に関する注意事項
WITHIN GROUP 句を使用する複数の LISTAGG 関数が 1 つのステートメントに含まれる場合、各 WITHIN GROUP 句で ORDER BY 値を使用する必要があります。
例えば、以下のステートメントはエラーを返します。
select listagg(sellerid) within group (order by dateid) as sellers, listagg(dateid) within group (order by sellerid) as dates from winsales;
以下のステートメントは正常に実行されます。
select listagg(sellerid) within group (order by dateid) as sellers, listagg(dateid) within group (order by dateid) as dates from winsales; select listagg(sellerid) within group (order by dateid) as sellers, listagg(dateid) as dates from winsales;
例
以下の例は、販売者 ID を集計し、販売者 ID 順で返します。
select listagg(sellerid, ', ') within group (order by sellerid) from sales where eventid = 4337; listagg ---------------------------------------------------------------------------------------------------------------------------------------- 380, 380, 1178, 1178, 1178, 2731, 8117, 12905, 32043, 32043, 32043, 32432, 32432, 38669, 38750, 41498, 45676, 46324, 47188, 47188, 48294
次の例では、DISTINCT を使用して一意の販売者 ID のリストを返します。
select listagg(distinct sellerid, ', ') within group (order by sellerid) from sales where eventid = 4337; listagg ------------------------------------------------------------------------------------------- 380, 1178, 2731, 8117, 12905, 32043, 32432, 38669, 38750, 41498, 45676, 46324, 47188, 48294
以下の例は、販売者 ID を集計し、日付順で返します。
select listagg(sellerid) within group (order by dateid) from winsales; listagg ------------- 31141242333
以下の例は、購入者 B について販売日付のパイプ区切りリストを返します。
select listagg(dateid,'|') within group (order by sellerid desc,salesid asc) from winsales where buyerid = 'b'; listagg --------------------------------------- 2003-08-02|2004-04-18|2004-04-18|2004-02-12
以下の例は、各購入者 ID について販売 ID のカンマ区切りリストを返します。
select buyerid, listagg(salesid,',') within group (order by salesid) as sales_id from winsales group by buyerid order by buyerid; buyerid | sales_id -----------+------------------------ a |10005,40001,40005 b |20001,30001,30004,30003 c |10001,20002,30007,10006