我在 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>