sql-server - Sum XML Value based on different attribute types
问题描述
I'm trying to extract number of adults, children and infants from the below example XML:
- Adults = AgeType 3
- Children = AgeType 2
- Infants = AgeType 1
and then count specifies how many of that age type. Correct result is:
- 35 Adults
- 5 Children
- 2 Infants
The below code returns the correct result, however I would like to avoid the cross apply
entering to the <Customer>
tags (as there are hundreds of millions per day).
declare @a table(a xml)
insert into @a
select '<Customers>
<Customer AgeType="3" Count="10" />
<Customer AgeType="3" Count="20" />
<Customer AgeType="3" Count="5" />
<Customer AgeType="2" Count="5" />
<Customer AgeType="1" Count="2" />
</Customers>'
select
sum(case when b.cust = 3 then b.cust*b.count_cust end)/3 as adt
,sum(case when b.cust = 2 then b.cust*b.count_cust end)/2 as chd
,sum(case when b.cust = 1 then b.cust*b.count_cust end)/1 as inf
from (
select c.value('(@AgeType)','int') As cust
,c.value('(@Count)','int') As count_cust
from @a cross apply a.nodes('Customers/Customer') as t(c)
) as b
Can anyone find any other logic that could be more effiecient? I was thinking using count
or sum
over the <Customer>
tags like below, however I can't get the correct reults.
a.value('count(Customers/Customer/@AgeType[.=3])','int') As adt
,a.value('count(Customers/Customer/@AgeType[.=2])','int') As chd
,a.value('count(Customers/Customer/@AgeType[.=1])','int') As inf
解决方案
更改您的 XPath
count(Customers/Customer/@AgeType[.=3])
至
sum(Customers/Customer[@AgeType = 3]/@Count)
总结所有成人(@AgeType
= 3)Customer
@Count
属性值。
对其他年龄类型遵循相同的模式。
推荐阅读
- c - 拆分 ac 文件并使用 Makefile
- r - 根据变量的长度分开
- sql - PostgreSQL 合并许多表以创建新表
- laravel - Laravel:An entity has 2 foreign keys how to display that entity which belong to the specific table?
- java - Is it possible to determine which rows are affected by SQL Server UPDATE?
- oracle - Knowage BI Oracle DataSource
- c++ - 为什么 boost::iterator_facade::operator[] 和 boost::iterator_range::operator[] 返回类型不一致
- typescript - 为什么 TS 仅在运行时不加载我的 npm 链接类?
- asp.net-core-2.1 - 即使我明确指定了 ASPNETCORE_ENVIRONENT=Development,ASP.NET Core 2.1 应用程序也没有获取 appsettings.Development.json。为什么?
- php - 在 codeigniter 中更改密码并抛出错误