[PostgreSQL]在group by查詢下拼接列字符串

首先創建group_concat聚集函數:

CREATE AGGREGATE group_concat(anyelement)
(
sfunc = array_append, -- 每行的操作函數,將本行append到數組裏
stype = anyarray, -- 聚集後返回數組類型
initcond = '{}' -- 初始化空數組
);

接着上一個SQL樣例:
在訂單明細表按poseason分組,把ticket_codeorder_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;

最後查詢結果截圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章