SQL嵌套在group by中选择

时间:2013-07-08 02:08:29

标签: sql sql-server

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

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>

1 个答案:

答案 0 :(得分: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。这两个都引用内部testing,因此它们只选择Department的非NULL值。