0

我在 SQL Server 中名为“测试”的表中有一些数据:

ID  Name    Department
1   Person1 IT
2   Person2 Finance
3   Person3 IT
4   Person4 IT
5   Person5 Finance

我使用的 SQL 查询是:

SELECT Department AS '@Department',
(
    SELECT Name
    FROM testing
    WHERE Department = Department
    FOR XML PATH ('Person'), TYPE
)
FROM testing
GROUP BY Department
FOR XML PATH ('Department'), TYPE

现在的问题是输出没有按部门分组。相反,所有人员都包含在财务中,然后又包含在 IT 中。

我哪里错了?

提前致谢


当前输出为:

<Department Department="Finance">
  <Person>
    <Name>Person1</Name>
  </Person>
  <Person>
    <Name>Person2</Name>
  </Person>
  <Person>
    <Name>Person3</Name>
  </Person>
  <Person>
    <Name>Person4</Name>
  </Person>
  <Person>
    <Name>Person5</Name>
  </Person>
</Department>
<Department Department="IT">
  <Person>
    <Name>Person1</Name>
  </Person>
  <Person>
    <Name>Person2</Name>
  </Person>
  <Person>
    <Name>Person3</Name>
  </Person>
  <Person>
    <Name>Person4</Name>
  </Person>
  <Person>
    <Name>Person5</Name>
  </Person>
</Department>

但我想要的输出是:

<Department Department="Finance">
  <Person>
    <Name>Person2</Name>
  </Person>
  <Person>
    <Name>Person5</Name>
  </Person>
</Department>
<Department Department="IT">
  <Person>
    <Name>Person1</Name>
  </Person>
  <Person>
    <Name>Person3</Name>
  </Person>
  <Person>
    <Name>Person4</Name>
  </Person>
</Department>
4

1 回答 1

1

您需要使用别名,因为您有两个对testing表的引用:

SELECT Department AS '@Department',
(
    SELECT Name
    FROM testing t2
    WHERE t2.Department = t.Department
    FOR XML PATH ('Person'), TYPE
)
FROM testing t
GROUP BY Department
FOR XML PATH ('Department'), TYPE

您的查询有Department = Department. 这两个都引用了 inner testing,所以他们只选择了 Department 的非 NULL 值。

于 2013-07-08T02:15:41.103 回答