LISTAGG 範圍函數 - Amazon Redshift

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

LISTAGG 範圍函數

對於查詢中的每一組,LISTAGG 範圍函數依據 ORDER BY 表達式來排序該組的列,然後將這些值串連成單一字串。

LISTAGG 是僅限於運算節點的函數。如果查詢未參考使用者定義的資料表或 Amazon Redshift 系統資料表,此函數會傳回錯誤。如需詳細資訊,請參閱 查詢目錄資料表

語法

LISTAGG( [DISTINCT] expression [, 'delimiter' ] ) [ WITHIN GROUP (ORDER BY order_list) ] OVER ( [PARTITION BY partition_expression] )

引數

DISTINCT

(選用) 此子句在串連值之前會從指定的表達式中消除重複值。結尾空格會忽略,所以字串 'a''a ' 視為重複值。LISTAGG 會使用第一個遇到的值。如需詳細資訊,請參閱 多餘空格的意義

aggregate_expression

任何有效表達式 (例如欄名),用於提供要彙總的值。忽略 NULL 值和空字串。

delimiter

(選用) 用來區隔串連值的字串常數。預設值為 NULL。

WITHIN GROUP (ORDER BY order_list)

(選用) 此子句指定彙總值的排序順序。只有在 ORDER BY 提供唯一排序時才可確定。預設是彙總所有列並傳回單一值。

OVER

用於指定視窗分割的子句。OVER 子句不能包含視窗排序或視窗框規格。

PARTITION BY partition_expression

(選用) 針對 OVER 子句中的每一個群組,設定記錄範圍。

傳回值

VARCHAR(MAX)。如果結果集大於 VARCHAR 大小上限 (64K – 1,或 65535),則 LISTAGG 會傳回下列錯誤:

Invalid operation: Result size exceeds LISTAGG limit

範例

下列範例使用 WINSALES 資料表。如需 WINSALES 資料表的描述,請參閱範圍函數範例的範例資料表

下列範例傳回賣方 ID 清單,依賣方 ID 排序。

select listagg(sellerid) within group (order by sellerid) over() from winsales; listagg ------------ 11122333344 ... ... 11122333344 11122333344   (11 rows)

下列範例傳回買方 B 的賣方 ID 清單,依日期排序。

select listagg(sellerid) within group (order by dateid) over () as seller from winsales where buyerid = 'b' ; seller --------- 3233 3233 3233 3233

下列範例以逗號分隔清單傳回買方 B 的銷售日期。

select listagg(dateid,',') within group (order by sellerid desc,salesid asc) over () as dates from winsales where buyerid = 'b'; dates ------------------------------------------- 2003-08-02,2004-04-18,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-04-18,2004-02-12

下列範例使用 DISTINCT 傳回買方 B 的唯一銷售日期清單。

select listagg(distinct dateid,',') within group (order by sellerid desc,salesid asc) over () as dates from winsales where buyerid = 'b'; dates -------------------------------- 2003-08-02,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-02-12 2003-08-02,2004-04-18,2004-02-12

下列範例以逗號分隔清單傳回每個買方 ID 的銷售 ID。

select buyerid, listagg(salesid,',') within group (order by salesid) over (partition by buyerid) as sales_id from winsales order by buyerid; +---------+-------------------------+ | buyerid | sales_id | +---------+-------------------------+ | a | 10005,40001,40005 | | a | 10005,40001,40005 | | a | 10005,40001,40005 | | b | 20001,30001,30003,30004 | | b | 20001,30001,30003,30004 | | b | 20001,30001,30003,30004 | | b | 20001,30001,30003,30004 | | c | 10001,10006,20002,30007 | | c | 10001,10006,20002,30007 | | c | 10001,10006,20002,30007 | | c | 10001,10006,20002,30007 | +---------+-------------------------+