sql-server – T SQL for XML PATH Group By Attribute或Element

我一直致力于使用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>

最佳答案 您可以将 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')
点赞