选择将同一列的所有行数据放入一列

时间:2015-12-31 09:21:31

标签: sql oracle pivot

我有一个表(TableA),有3列(ColA,ColB,ColC)

ColA和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

,即将所有结果行放入一行,该列的值为相应列。

1 个答案:

答案 0 :(得分: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';

SqlFiddleDemo2 SqlFiddleDemo3