你可以使用LISTAGG
:
WITH tableA AS
(
SELECT '001' AS COLA, 'AA1' AS COLB, 460 AS COLC FROM dual
UNION ALL SELECT '001','AB1',380 FROM dual
UNION ALL SELECT '001','AC1',950 FROM dual
)
SELECT DISTINCT
LISTAGG(COLA, ', ') WITHIN GROUP (ORDER BY 1) AS COLA,
LISTAGG(COLB, ', ') WITHIN GROUP (ORDER BY 1) AS COLB,
LISTAGG(COLC, ', ') WITHIN GROUP (ORDER BY 1) AS COLC
FROM tableA
WHERE COLA = '001';
SqlFiddleDemo
輸出:
╔════════════════╦════════════════╦═══════════════╗
║ COLA ║ COLB ║ COLC ║
╠════════════════╬════════════════╬═══════════════╣
║ 001, 001, 001 ║ AA1, AB1, AC1 ║ 380, 460, 950 ║
╚════════════════╩════════════════╩═══════════════╝
但我也補充OVER
子句和從COLA
刪除重複:
WITH tableA AS
(
SELECT '001' AS COLA, 'AA1' AS COLB, 460 AS COLC FROM dual
UNION ALL SELECT '001','AB1',380 FROM dual
UNION ALL SELECT '001','AC1',950 FROM dual
)
SELECT DISTINCT
COLA,
LISTAGG(COLB, ', ') WITHIN GROUP (ORDER BY 1) OVER(PARTITION BY COLA) AS COLB,
LISTAGG(COLC, ', ') WITHIN GROUP (ORDER BY 1) OVER(PARTITION BY COLA) AS COLC
FROM tableA
WHERE COLA = '001';
SqlFiddleDemo2
SqlFiddleDemo3
可能重複http://stackoverflow.com/questions/4686543/sql-query-to-concatenate-來自多行的列值從 – minatverma