SQL:将行与列中的逗号分隔值合并
Posted
技术标签:
【中文标题】SQL:将行与列中的逗号分隔值合并【英文标题】:SQL: Merging rows with comma separated values in columns 【发布时间】:2014-11-11 11:43:14 【问题描述】:我们有一张这样的表:
Group | User | Team
-------------------
Grp1 | U1 | T1,T2
Grp1 | U2 | T1,T2,T3
Grp1 | U3 | T4
Grp2 | U4 | T2,T4
Grp2 | U5 | T5
我想创建一个包含如下数据的视图:
Group | Teams
-------------
Grp1 | T1,T2,T3,T4
Grp2 | T2,T4,T5
有人可以帮帮我吗?我尝试了一些尝试和错误,最后我处于一个我什至不确定从现在开始的状态
【问题讨论】:
【参考方案1】:这是我的方法。 我正在使用游标,但您也可以在 while 循环中执行此操作。 唯一的问题是新表中的团队并不明显,但我认为您可以使用字符串命令来解决问题。
CREATE TABLE #tbl1 ([GROUP] varchar(20), [USER] VARCHAR(20), team VARCHAR(20))
INSERT INTO #tbl1 ( [GROUP], [USER],team )
VALUES ( 'Grp1', 'U1', 'T1,T2'), ( 'Grp1', 'U2', 'T3,T4'), ( 'Grp1', 'U3', 'T4'),
( 'Grp2', 'U1', 'T1,T2'), ( 'Grp2', 'U2', 'T3,T4')
CREATE TABLE #tbl2 ([GROUP] varchar(20), team VARCHAR(20))
DECLARE @ListOfteams VARCHAR(max)
DECLARE @grp VARCHAR(20)
DECLARE Curs CURSOR FAST_FORWARD
FOR
SELECT DISTINCT [GROUP]
FROM #tbl1 AS T
OPEN Curs
FETCH NEXT FROM Curs INTO @grp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @ListOfteams= ''
SELECT @ListOfteams= @ListOfteams+ [Team] + ',' FROM #tbl1 AS CL WHERE CL.[GROUP] = @grp ORDER BY [CL].[USER]
INSERT INTO #tbl2 ( [GROUP],team )
SELECT DISTINCT @grp,
SUBSTRING(@ListOfteams, 1, LEN(@ListOfteams)-1)
FROM #tbl1 AS T
WHERE T.[GROUP] = @grp;
FETCH NEXT FROM Curs INTO @grp
END
CLOSE Curs
DEALLOCATE Curs;
SELECT *
FROM #tbl2 AS T
下面是它的工作原理:http://rextester.com/BYK57259
+-------+----------------+
| GROUP | team |
+-------+----------------+
| Grp1 | T1,T2,T3,T4,T4 |
| Grp2 | T1,T2,T3,T4 |
+-------+----------------+
【讨论】:
很棒的家伙...你们真的是救生员!!非常感谢! @pradeep 没问题,伙计!如果您能通过单击向上箭头按钮为我们的回复投票,那就太好了:)【参考方案2】:这里是这样做的,首先将逗号分隔的团队名称转换为基于组的单独行,然后采用唯一的团队 grp 和团队名称。现在对唯一的团队名称应用 listagg 函数来获得结果。
with t as
(
select 'Grp1' grp,'U1' user1,'T1,T2' team from dual
union all
select 'Grp1','U2','T1,T2,T3' from dual
union all
select 'Grp1','U3','T4' from dual
union all
select 'Grp2','U4','T2,T4' from dual
union all
select 'Grp2','U5','T5' from dual
),
g as
(
select distinct grp, regexp_substr(team,'[^,]+',1,level) team1
from t
connect by level <= LENGTH(REGEXP_REPLACE(team, '[^,]+')) + 1
--group by grp
)
select grp,listagg(team1,',') within group (order by team1) from g
group by grp;
这是我得到的输出
+----+-------------------------------------------+
|GRP ||Teams
+----+-------------------------------------------+
|Grp1|T1,T2,T3,T4 |
|Grp2|T2,T4,T5 |
+----+-------------------------------------------+
【讨论】:
很棒的家伙......你们真的是救生员!!非常感谢以上是关于SQL:将行与列中的逗号分隔值合并的主要内容,如果未能解决你的问题,请参考以下文章