将列值连接到逗号分隔的字符串中

时间:2013-01-08 15:56:11

标签: sql sql-server

  

可能重复:
  Concat groups in SQL Server

请查看下面的表格结构:

CREATE TABLE Person (ID INT, Name varchar(30), primary key(ID))
CREATE TABLE Warnings (ID INT, PersonID INT, Description VARCHAR(100), FOREIGN KEY (PersonID) REFERENCES Person(ID))

INSERT INTO Person (1,'Robert')
INSERT INTO Person (2,'Maria')

INSERT INTO Warnings (1,1,'Spitting')
INSERT INTO Warnings (2,1,'Punching')
INSERT INTO Warnings (3,1,'Pinching')

INSERT INTO Warnings (4,2,'Offenive words')
INSERT INTO Warnings (5,2,'Lateness')

我想获得这样的输出:

Name    Offences
Robert  Spitting,Punching, Pinching
Maria   Offensive words, Lateness

我查看了数据透视表和以下函数:STUFF和QUOTENAME。我还没有找到解决方案。与某人有关的犯罪数量未知。

1 个答案:

答案 0 :(得分:2)

SELECT
     a.[Name],
     STUFF(
         (SELECT ',' + [Description]
          FROM Warnings
          WHERE [PersonID] = a.[ID]
          FOR XML PATH (''))
          , 1, 1, '')  AS Offences
FROM Person AS a
     INNER JOIN Warnings b
        ON a.ID = b.PersonID
GROUP BY a.ID,a.[Name]