将相关表中列的值连接成一个字符串

时间:2014-02-21 18:10:01

标签: sql sql-server tsql

我在 SQL Server 2008 中有2个表(1-n)。

示例:1个人 - 'n'地址

我想选择人员数据并将相关地址区域列入一个列(连接)

ID  Name
------------------------------------------
1   John Smith
2   Daniel

PersonID  DistrictName
------------------------------------------
1         Brooklin
1         SoHo
2         Upper West Side
2         Harlem

SELECT desired
------------------------------------------
John Smith   Brooklin, SoHo
Daniel       Upper West Side, Harlem

我怎么能在tsql中做到这一点?

2 个答案:

答案 0 :(得分:2)

“经典”方式是使用FOR XML PATH。这个问题有重复,但即使遵循这些问题,使查询正确也不容易;

SELECT name,
  STUFF((
    SELECT ', ', districtname AS 'data()' 
    FROM district 
    WHERE ID=PersonID
    FOR XML PATH('')), 1, 2, '') districts
FROM person;

An SQLfiddle to test with

答案 1 :(得分:1)

测试数据

DECLARE @Person TABLE(ID INT,Name VARCHAR(100))
INSERT INTO @Person VALUES
(1,'John Smith'),(2,'Daniel')

DECLARE @Person_Address TABLE(PersonID INT,DistrictName VARCHAR(1000))
INSERT INTO @Person_Address VALUES
(1,'Brooklin'),(1,'SoHo'),
(2,'Upper West Side'),(2,'Harlem')

<强>查询

SELECT P.Name
      ,STUFF((SELECT ', ' + DistrictName [text()]
              FROM @Person_Address
              WHERE PersonID = P.ID
              FOR XML PATH(''),TYPE).
              value('.','NVARCHAR(MAX)'),1 ,2,'') AS Address
FROM @Person P
GROUP BY P.Name,P.ID

结果集

╔════════════╦═════════════════════════╗
║    Name    ║         Address         ║
╠════════════╬═════════════════════════╣
║ Daniel     ║ Upper West Side, Harlem ║
║ John Smith ║ Brooklin, SoHo          ║
╚════════════╩═════════════════════════╝