根据不同的属性类型求和 XML 值
Sum XML Value based on different attribute types
我正在尝试从以下示例中提取成人、children 和婴儿的数量 XML:
- 成人 = 3 岁
- Children = 年龄类型 2
- 婴儿 = AgeType 1
然后计数指定该年龄类型的数量。正确的结果是:
- 35 位成人
- 5 Children
- 2 个婴儿
下面的代码 returns 是正确的结果,但是我想避免 cross apply
进入 <Customer>
标签(因为每天有数亿)。
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
谁能找到其他更有效的逻辑?我正在考虑在 <Customer>
标签上使用 count
或 sum
,如下所示,但是我无法获得正确的结果。
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
属性值。
对其他年龄类型遵循相同的模式。
我正在尝试从以下示例中提取成人、children 和婴儿的数量 XML:
- 成人 = 3 岁
- Children = 年龄类型 2
- 婴儿 = AgeType 1
然后计数指定该年龄类型的数量。正确的结果是:
- 35 位成人
- 5 Children
- 2 个婴儿
下面的代码 returns 是正确的结果,但是我想避免 cross apply
进入 <Customer>
标签(因为每天有数亿)。
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
谁能找到其他更有效的逻辑?我正在考虑在 <Customer>
标签上使用 count
或 sum
,如下所示,但是我无法获得正确的结果。
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
从
更改您的 XPathcount(Customers/Customer/@AgeType[.=3])
到
sum(Customers/Customer[@AgeType = 3]/@Count)
总结所有成人(@AgeType
= 3) Customer
@Count
属性值。
对其他年龄类型遵循相同的模式。