Oracle SQL 带排除项的数据透视表
Oracle SQL Pivot with exclusions
我有一组数据:
SELECT * FROM costings
输出:
section von part price
5 2013000043 3019 -15000
5 2014000041 1547 18000
5 2014000041 3019 -15000
5 2014000071 1547 18000
5 2014000071 3019 -15000
5 2016000018 1547 12000
5 2016000018 3019 -10000
5 2014000081 1549 3244.8
5 2014000081 3019 -1474
5 2015000040 1549 3244.8
5 2015000040 3019 -1474
5 2016000021 1549 2506.8
5 2016000021 3019 -1474
6 2013000069 1566 5760
6 2013000069 3013 -4800
6 2013000128 1566 7200
6 2013000128 3013 -6000
6 2014000060 1566 5760
我想像这样使用 pivot 输出数据:
section 1547 1549 1566
5 -40000 -4422 null
6 null null -10800
现在,预期价值金额背后的逻辑是,每个 von
您有多个 part
个数字。
以2014000041
为例,有1547
& 3019
.
我想要的是以 15
开头的 part
数字作为支点 header,但 SUM
仅对 part
处的价格求和不以 15
.
开头
如果您知道以“15”开头的值,那么一个想法是沿 section
/von
进行预聚合,然后重新聚合结果:
select section,
sum(case when part15 = '1547' then price_not15 end) as part_1547,
sum(case when part15 = '1549' then price_not15 end) as part_1549,
sum(case when part15 = '1566' then price_not15 end) as part_1566
from (select section, von,
max(case when part like '15%' then part end) as part15,
sum(case when part not like '15%' then price end) as price_not15
from costings
group by section, von
) c
group by section;
这假设每个 section
/von
组合只有一个部分以 15
开头。
我有一组数据:
SELECT * FROM costings
输出:
section von part price
5 2013000043 3019 -15000
5 2014000041 1547 18000
5 2014000041 3019 -15000
5 2014000071 1547 18000
5 2014000071 3019 -15000
5 2016000018 1547 12000
5 2016000018 3019 -10000
5 2014000081 1549 3244.8
5 2014000081 3019 -1474
5 2015000040 1549 3244.8
5 2015000040 3019 -1474
5 2016000021 1549 2506.8
5 2016000021 3019 -1474
6 2013000069 1566 5760
6 2013000069 3013 -4800
6 2013000128 1566 7200
6 2013000128 3013 -6000
6 2014000060 1566 5760
我想像这样使用 pivot 输出数据:
section 1547 1549 1566
5 -40000 -4422 null
6 null null -10800
现在,预期价值金额背后的逻辑是,每个 von
您有多个 part
个数字。
以2014000041
为例,有1547
& 3019
.
我想要的是以 15
开头的 part
数字作为支点 header,但 SUM
仅对 part
处的价格求和不以 15
.
如果您知道以“15”开头的值,那么一个想法是沿 section
/von
进行预聚合,然后重新聚合结果:
select section,
sum(case when part15 = '1547' then price_not15 end) as part_1547,
sum(case when part15 = '1549' then price_not15 end) as part_1549,
sum(case when part15 = '1566' then price_not15 end) as part_1566
from (select section, von,
max(case when part like '15%' then part end) as part15,
sum(case when part not like '15%' then price end) as price_not15
from costings
group by section, von
) c
group by section;
这假设每个 section
/von
组合只有一个部分以 15
开头。