T SQL for XML PATH Group By Attribute或Element

时间:2017-04-25 07:18:47

标签: sql-server database tsql for-xml

我一直致力于使用PATH模式的T-SQL FOR XML来创建基于逐个字段的层次结构。 以下是我的查询和输出。请帮助我提出宝贵的建议。谢谢。美好的一天!!!

select e.department_id AS [@DepartmentID],
d.DEPARTMENT_NAME AS [@DepartmentName],
e.EMPLOYEE_ID AS [EmployeeInfo/EmployeeID],
e.FIRST_NAME AS [EmployeeInfo/FirstName],
e.LAST_NAME AS [EmployeeInfo/LastName]
from employees e
JOIN departments d 
ON e.department_id = d.department_id
GROUP BY e.department_id,d.DEPARTMENT_NAME,
e.EMPLOYEE_ID,e.FIRST_NAME,e.LAST_NAME
FOR XML PATH ('Department'), ROOT ('Departments')

输出:

 <Departments>
  <Department DepartmentID="10">
    <EmployeeInfo>
      <EmployeeID>111</EmployeeID>
      <FirstName>John</FirstName>
      <LastName>Chen</LastName>
    </EmployeeInfo>
  </Department>
  <Department DepartmentID="10">
    <EmployeeInfo>
      <EmployeeID>201</EmployeeID>
      <FirstName>steven</FirstName>
      <LastName>Whalen</LastName>
    </EmployeeInfo>
  </Department>
  <Department DepartmentID="30">
    <EmployeeInfo>
      <EmployeeID>105</EmployeeID>
      <FirstName>ANIRUDH</FirstName>
      <LastName>RAMESH</LastName>
    </EmployeeInfo>
  </Department>
  <Department DepartmentID="30">
    <EmployeeInfo>
      <EmployeeID>115</EmployeeID>
      <FirstName>Den</FirstName>
      <LastName>Raphaely</LastName>
    </EmployeeInfo>
  </Department>
<Departments>

所需的输出是:

<Departments>
  <Department DepartmentID="10">
    <EmployeeInfo>
      <EmployeeID>111</EmployeeID>
      <FirstName>John</FirstName>
      <LastName>Chen</LastName>
    </EmployeeInfo>
    <EmployeeInfo>
      <EmployeeID>201</EmployeeID>
      <FirstName>steven</FirstName>
      <LastName>Whalen</LastName>
    </EmployeeInfo>
  </Department>
  <Department DepartmentID="30">
    <EmployeeInfo>
      <EmployeeID>105</EmployeeID>
      <FirstName>ANIRUDH</FirstName>
      <LastName>RAMESH</LastName>
    </EmployeeInfo>
    <EmployeeInfo>
      <EmployeeID>115</EmployeeID>
      <FirstName>Den</FirstName>
      <LastName>Raphaely</LastName>
    </EmployeeInfo>
  </Department>
<Departments>

2 个答案:

答案 0 :(得分:2)

您可以将TYPE用于嵌套xml

SELECT 
      d.department_id AS [@DepartmentID],
      d.DEPARTMENT_NAME AS [@DepartmentName], 
      (
         SELECT 
                e.EMPLOYEE_ID AS EmployeeID,
                e.FIRST_NAME AS [FirstName],
                e.LAST_NAME AS [LastName]  
         FROM employees e
         WHERE e.department_id = d.department_id
         FOR XML PATH ('EmployeeInfo'), TYPE
      )
FROM departments d 
FOR XML PATH ('Department'), ROOT ('Departments')

答案 1 :(得分:0)

不确定,我们是否可以回答我们自己的问题。  我和我我的一位同事为此查询找到了另一种解决方案,但使用了AUTO模式。

select d.DEPARTMENT_ID as [DepartmentID],e.EMPLOYEE_ID as 
[EmployeeID],e.first_name as [EmployeeName],e.SALARY as [Salary]
from [departments] d
inner join [employees] e
on e.DEPARTMENT_ID = d.DEPARTMENT_ID
order by 1,4
for xml AUTO, Root ('Employees'), ELEMENTS