首先創建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;
最後查詢結果截圖: