按升序获取连续行

时间:2011-04-19 05:03:00

标签: sql sql-server-2005 tsql

  

可能重复:
  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已分组,而逗号分隔的消息按升序排列。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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