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;

最后查詢結果截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM