sql - 如何在 SQL Server 中对 XML 格式数据使用 Group by 格式
问题描述
我有这些数据。
declare @T table
(
ID int,
[subject] varchar(30),
Marks int
)
insert into @T values
(1, 'Maths',78),
(1, 'Science',89),
(2, 'Maths',90),
(3, 'Maths',91),
(4, 'Maths',92)
我试过这个查询:
SELECT ID
,(SELECT t1.* FOR XML PATH('body'),TYPE) AS TheRowAsXml
FROM @T as t1
但它为每个条目提供 1 行。
我想按 ID 分组
我的预期输出如下:
<body>
<ID>1</ID>
<subject>Maths</subject>
<Marks>78</Marks>
<subject>Science</subject>
<Marks>89</Marks>
</body>
对于 ID 1 等
请任何建议将不胜感激
解决方案
您可以使用子查询生成,如下所示:
declare @T table
(
ID int,
[subject] varchar(30),
Marks int
)
insert into @T values
(1, 'Maths',78),
(1, 'Science',89),
(2, 'Maths',90),
(3, 'Maths',91),
(4, 'Maths',92)
--SELECT id, subject, marks from @T WHERE id = 1
--for xml path('')
SELECT distinct id,CONCAT('<body><ID>',cast(id as varchar(10)),'</ID>',
(SELECT subject, marks from @T WHERE id = t.id
for xml path('')
),'</body>') as Rowxml
from @t as t
+----+-------------------------------------------------------------------------------------------------------------+
| id | Rowxml |
+----+-------------------------------------------------------------------------------------------------------------+
| 1 | <body><ID>1</ID><subject>Maths</subject><marks>78</marks><subject>Science</subject><marks>89</marks></body> |
| 2 | <body><ID>2</ID><subject>Maths</subject><marks>90</marks></body> |
| 3 | <body><ID>3</ID><subject>Maths</subject><marks>91</marks></body> |
| 4 | <body><ID>4</ID><subject>Maths</subject><marks>92</marks></body> |
+----+-------------------------------------------------------------------------------------------------------------+
更新
一种更清洁的方法
SELECT id "ID",max(t2.rowxml)
from @t as t
CROSS APPLY
(SELECT subject, marks
from @T WHERE id = t.id
for xml path('')
) as t2(rowxml)
group by t.id
for xml path('body')
推荐阅读
- react-native-web - SectionList scrollToLocation 无法在 React Native Web 中滚动
- wpf - 如何获取WPF平台中控件的实际宽度和实际高度
- visual-studio-2019 - 如何删除 Blazor 代码块背景颜色?
- unity3d - 为什么我的网格只有一部分在屏幕外时会完全消失
- python - 如何在列的值中选择一些字符并使用该值创建一个新列
- javascript - 得到
- 值并使用 jquery onclick 分配给 iframe 中的 url 参数
- javascript - 如何在页面更改之间保留 chrome 扩展覆盖?
- php - Laravel,如果商店具有相同的组ID,则获取一组商店的所有订单
- java - 为什么这段代码不计算税收减去收入来打印带回家的工资?税务实验室
- c# - 如何将每个操作结果的数组写入新数组