计算地理小计
calculate subtotal for geography
我有以下table
示例 1:
L1lEVEL L1lEVEL Level 3 Amount
EMEA France France excl Midcaps 100
EMEA France Midcaps France 203
EMEA Germany Germany 409
EMEA Italie Italie 821
EMEA Benelux Netherland 1645
EMEA Benelux Belgium 3293
EMEA UK UK 6589
EMEA Iberia Iberia 13181
Americas US US 26365
Americas CANADA CANADA 52733
我需要专门为 EMEA 计算总计和小计:我有两个小计 Emea DM 和 EMEA EXL DM
- EMEA DM:法国不包括中盘股、意大利、比利时,当比利时的金额 => 3000
- EMEA EXL DM:除法国以外的级别,不包括中型股、意大利、比利时
当比利时的金额 < 3000
当比利时的金额 > 3000 时
EMEA 100+203+09+8211645+3293+6589+131181
Emea DM 203+821+3293
EMEA EXL DM: EMEA -EMEA DM
示例 2:
L1lEVEL L1lEVEL Level 3 Amount
EMEA France France excl Midcaps 100
EMEA France Midcaps France 203
EMEA Germany Germany 409
EMEA Italie Italie 821
EMEA Benelux Netherland 1645
EMEA Benelux Belgium 10
EMEA UK UK 6589
EMEA Iberia Iberia 13181
Americas US US 26365
Americas CANADA CANADA 52733
当比利时的金额 = 10 < 3000
EMEA 100+203+09+8211645+3293+6589+131181
Emea DM 203+821
EMEA EXL DM: EMEA -EMEA DM
如果我没听错的话,你可以做条件聚合。横向连接很方便,可以避免重复条件表达式:
select
sum(amount) emea,
sum(case when region = 'EMEA DM' then amount else 0 end) as emea_dm,
sum(case when region = 'EMEA EXL DM' then amount else 0 end) as emea_exl_dm
from mytable t
cross apply (values (
case when (level2 = 'France' and level3 = 'France excl Midcaps')
or level3 = 'Italie'
or (level3 = 'Belgium' and amount > 3000)
then 'EMEA DM' else 'EMEA EXL DM' end
)) as x(region)
where t.level1 = 'EMEA'
你的问题对列的名称不是很清楚;我假设 level1
、level2
和 level3
。
我有以下table 示例 1:
L1lEVEL L1lEVEL Level 3 Amount
EMEA France France excl Midcaps 100
EMEA France Midcaps France 203
EMEA Germany Germany 409
EMEA Italie Italie 821
EMEA Benelux Netherland 1645
EMEA Benelux Belgium 3293
EMEA UK UK 6589
EMEA Iberia Iberia 13181
Americas US US 26365
Americas CANADA CANADA 52733
我需要专门为 EMEA 计算总计和小计:我有两个小计 Emea DM 和 EMEA EXL DM
- EMEA DM:法国不包括中盘股、意大利、比利时,当比利时的金额 => 3000
- EMEA EXL DM:除法国以外的级别,不包括中型股、意大利、比利时 当比利时的金额 < 3000
当比利时的金额 > 3000 时
EMEA 100+203+09+8211645+3293+6589+131181
Emea DM 203+821+3293
EMEA EXL DM: EMEA -EMEA DM
示例 2:
L1lEVEL L1lEVEL Level 3 Amount
EMEA France France excl Midcaps 100
EMEA France Midcaps France 203
EMEA Germany Germany 409
EMEA Italie Italie 821
EMEA Benelux Netherland 1645
EMEA Benelux Belgium 10
EMEA UK UK 6589
EMEA Iberia Iberia 13181
Americas US US 26365
Americas CANADA CANADA 52733
当比利时的金额 = 10 < 3000
EMEA 100+203+09+8211645+3293+6589+131181
Emea DM 203+821
EMEA EXL DM: EMEA -EMEA DM
如果我没听错的话,你可以做条件聚合。横向连接很方便,可以避免重复条件表达式:
select
sum(amount) emea,
sum(case when region = 'EMEA DM' then amount else 0 end) as emea_dm,
sum(case when region = 'EMEA EXL DM' then amount else 0 end) as emea_exl_dm
from mytable t
cross apply (values (
case when (level2 = 'France' and level3 = 'France excl Midcaps')
or level3 = 'Italie'
or (level3 = 'Belgium' and amount > 3000)
then 'EMEA DM' else 'EMEA EXL DM' end
)) as x(region)
where t.level1 = 'EMEA'
你的问题对列的名称不是很清楚;我假设 level1
、level2
和 level3
。