SQL递归合并

时间:2010-01-13 13:12:04

标签: sql sql-server tsql

我正在尝试创建一个包含所有引用地址城市的列。

DECLARE @AddressList nvarchar(max)
SELECT @AddressList = COALESCE(@AddressList + ' ', '') + City  FROM [Address]

SELECT
    Employee.*, 
    (SELECT @AddressList) AS AddressCities
FROM Employee

但我不知道把WHERE子句放在哪里。

...
    (SELECT @AddressList WHERE EmployeeId = Employee.EmployeeId) AS AddressCities
...

上述测试不起作用..

表模式是:

  

员工
  雇员
  名称

     

地址
  街
  市
  EMPLOYEEID

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望在该列的一列中显示所有 Cities 。所以你希望 GROUP BY和CONCAT

使用Sql Server 2005,试试这个(工作示例)

DECLARE @Employee TABLE(
        EmployeeId INT,
        NAME VARCHAR(100)
)

INSERT INTO @Employee (EmployeeId,[NAME]) SELECT 1, 'A'
INSERT INTO @Employee (EmployeeId,[NAME]) SELECT 2, 'B'

DECLARE @Address TABLE(
        Street VARCHAR(50),
        City VARCHAR(50),
        EmployeeId INT
)

INSERT INTO @Address (Street,City, EmployeeId) SELECT 'A','A', 1
INSERT INTO @Address (Street,City, EmployeeId) SELECT 'B','B', 1
INSERT INTO @Address (Street,City, EmployeeId) SELECT 'C','C', 1
INSERT INTO @Address (Street,City, EmployeeId) SELECT 'D','D', 2
INSERT INTO @Address (Street,City, EmployeeId) SELECT 'E','E', 2
INSERT INTO @Address (Street,City, EmployeeId) SELECT 'F','F', 2


SELECT  e.EmployeeId,
        e.[NAME],
        (
            SELECT  al.City + ','
            FROM    @Address al
            WHERE   al.EmployeeId = e.EmployeeId
            FOR XML PATH('')
        )
FROM    @Employee e
GROUP BY e.EmployeeId,
        e.[NAME]

答案 1 :(得分:0)

需要有关“包含所有城市的列”的含义的更多信息。你想要的与以下内容有什么不同可能有助于你说出问题

SELECT e.EmployeeId,e.Name,a.City
FROM Employee e
INNER JOIN Address a ON a.EmployeeId = e.EmployeeId
GROUP BY e.EmployeeId,e.Name

- 更新

我想我明白你的意思,你想要的是:

EmployeeID | Name | Address
1          | John | 'London','Paris','Rome'
2          | Jane | 'New York','Miami'