2015-12-31 52 views
1

我有一個表(表A)有3列(可樂,COLB,COLC)選擇獲取所有行同一列的數據合併到一列

可樂COLB是主鍵

select * 
from TableA 
where ColA = '001'; 

給我這個

COLA COLB  COLC 
---- ----- -------- 
001 AA1  460 
001 AB1  380 
001 AC1  950 

我需要這個結果在這個格式

COLA   COLB   COLC 
----------- ----------- -------- 
001,001,001 AA1,AB1,AC1 460,380,950 

即將所有行的結果行分成一行,並將該列的值分配給相應的列。

+0

可能重複http://stackoverflow.com/questions/4686543/sql-query-to-concatenate-來自多行的列值從 – minatverma

回答

2

你可以使用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'; 

SqlFiddleDemo2SqlFiddleDemo3

+1

您值得擁有一枚獎章。 –

相關問題