2011-04-19 66 views
0

可能重複:
SQL Server: Can I Comma Delimit Multiple Rows Into One Column?獲取升序級聯排

腳本: -

CREATE TABLE Category (
    ID int, 
    ErrorMessage nvarchar(200) 
) 


INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (1, 'efgh') 

INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (1, 'abcd') 

INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (1, 'ijkl') 

INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (2, 'efgh') 

INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (2, 'abcd') 

INSERT INTO Category 
    (ID, ErrorMessage) 
VALUES 
    (2, 'ijkl') 

預計輸出

Id     ErrorMessage 
---------------------------------- 
1     abcd,efgh,ijkl 
2     abcd,efgh,ijkl 

請注意,類別ID是分組的,用逗號分隔的消息按升序排列。

+0

什麼版本的SQL Server? – 2011-04-19 05:06:20

+0

Sql server 2005 – 2011-04-19 05:06:44

回答

2
Select C.Id 
    , Stuff(
     (
     Select ', ' + C1.ErrorMessage 
     From Category As C1 
     Where C1.Id = C.Id 
     Order By C1.ErrorMessage 
     For Xml Path('') 
     ), 1, 2, '') As Categories 
From Category As C 
Group By C.Id 
+0

您可以在不使用XML類型和值提取的情況下獲得XML授權 – RichardTheKiwi 2011-04-19 05:09:35

2
select A.ID, STUFF((
    select ','+B.ErrorMessage 
    from Category B 
    where B.ID = A.ID 
    order by B.ErrorMessage 
    for xml path ('a'), type).value('.','nvarchar(max)'),1,1,'') 
from Category A 
group by A.ID 
order by A.ID