首先創建group_concat聚集函數:
CREATE AGGREGATE group_concat(anyelement)
(
sfunc = array_append, -- 每行的操作函數,將本行append到數組里
stype = anyarray, -- 聚集后返回數組類型
initcond = '{}' -- 初始化空數組
);
接着上一個SQL樣例:
在訂單明細表按po和season分組,把ticket_code和order_id去除重復並且拼接起來
--wp_order_detail
SELECT
po,
season,
array_to_string( group_concat ( DISTINCT ticket_code ), ',' ) AS ticket_codes,
array_to_string( group_concat ( DISTINCT order_id ), ',' ) AS order_ids
FROM
wp_order_detail
WHERE
exists (select 1 from wp_order orders where orders.id = order_id and type = 'Po')
GROUP BY
po,
season;
最后查詢結果截圖:

