如何将此Sql列连接到单个单元格? [重复]

时间:2022-10-28 15:57:01

This question already has an answer here:

这个问题在这里已有答案:

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:

如何将此Sql列连接到单个单元格? [重复]

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:

如何将此Sql列连接到单个单元格? [重复]

WORKING FIDDLE