选择将同一列的所有行数据放入一列
Posted
技术标签:
【中文标题】选择将同一列的所有行数据放入一列【英文标题】:Select to get all rows data of same column into one column 【发布时间】:2015-12-31 09:21:31 【问题描述】:我有一个包含 3 列 (ColA,ColB,ColC) 的表 (TableA)
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
即所有结果行合并到一行中,该列的值对应于相应列。
【问题讨论】:
可能重复***.com/questions/4686543/… 【参考方案1】:你可以使用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
【讨论】:
你先生应该获得奖牌。以上是关于选择将同一列的所有行数据放入一列的主要内容,如果未能解决你的问题,请参考以下文章