This question already has an answer here:
这个问题在这里已有答案:
- How to concatenate text from multiple rows into a single text string in SQL server? 44 answers
如何将多行中的文本连接成SQL Server中的单个文本字符串? 44个答案
ClassName BookCode
First 2
Second 2
Third 2
First 3
Fourth 3
Fifth 3
I want to concatenate this into like this :
我想将此连接成这样:
ClassName BookCode
First,Second,Third 2
First,Fourth,Fifth 3
2 个解决方案
#1
0
try this query:
试试这个查询:
select distinct t1.BookCode,
STUFF((SELECT distinct ',' + t2.ClassName
from yourtable t2
where t1.BookCode = t2.BookCode
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,0,',') ClassName
from yourtable t1;
NOT TESTED.
#2
0
Try this
SELECT
Distinct BookCode,
(
SELECT ClassName +','
FROM table1 t2
WHERE t2.BookCode= t1.BookCode
FOR XML PATH('')
) Concatenated
FROM table1 t1
Output:
WORKING FIDDLE
#1
0
try this query:
试试这个查询:
select distinct t1.BookCode,
STUFF((SELECT distinct ',' + t2.ClassName
from yourtable t2
where t1.BookCode = t2.BookCode
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,0,',') ClassName
from yourtable t1;
NOT TESTED.
#2
0
Try this
SELECT
Distinct BookCode,
(
SELECT ClassName +','
FROM table1 t2
WHERE t2.BookCode= t1.BookCode
FOR XML PATH('')
) Concatenated
FROM table1 t1
Output: