使用 SQL 中的 stuff() 将多个值连接到单个列
Concatenate multiple values to a single column using stuff() in SQL
ID | NAME
----|--------
1 |Ann
2 |Jake
1 |Julie
3 |Paul
2 |Shane
4 |Kumi
我想使用 stuff()
连接值,如下所示。并且单个值不应受到 stuff()
函数的影响。
ID | NAME
----|--------
1 |Ann,Julie
2 |Jake,Shane
3 |Paul
4 |Kumi
怎么做?
STUFF 不进行连接,它用于 XML,this.Stuff 仅根据选择
替换值
select id,
stuff((select ','+name from #t1 t2 where t1.id=t2.id for xml path('')),1,1,'')
from #t1 t1
group by id
CREATE TABLE #A
(ID INT, NAME VARCHAR(10))
INSERT INTO #A VALUES
(1,'ANN'),
(2,'JAKE'),
(1,'JULIE'),
(3,'PAUL'),
(2,'SHANE'),
(4,'KUMI')
SELECT DISTINCT ID ,
STUFF((SELECT ','+NAME
FROM #A T1
WHERE T1.ID=T2.ID
FOR XML PATH('')),1,1,'') FROM #A T2
ID | NAME
----|--------
1 |Ann
2 |Jake
1 |Julie
3 |Paul
2 |Shane
4 |Kumi
我想使用 stuff()
连接值,如下所示。并且单个值不应受到 stuff()
函数的影响。
ID | NAME
----|--------
1 |Ann,Julie
2 |Jake,Shane
3 |Paul
4 |Kumi
怎么做?
STUFF 不进行连接,它用于 XML,this.Stuff 仅根据选择
替换值select id,
stuff((select ','+name from #t1 t2 where t1.id=t2.id for xml path('')),1,1,'')
from #t1 t1
group by id
CREATE TABLE #A
(ID INT, NAME VARCHAR(10))
INSERT INTO #A VALUES
(1,'ANN'),
(2,'JAKE'),
(1,'JULIE'),
(3,'PAUL'),
(2,'SHANE'),
(4,'KUMI')
SELECT DISTINCT ID ,
STUFF((SELECT ','+NAME
FROM #A T1
WHERE T1.ID=T2.ID
FOR XML PATH('')),1,1,'') FROM #A T2