我有以下数据:
case "$(whoami)" in
<USER1>|<USER2>)
alias python="/usr/bin/python2.7"
;;
我事先知道Key1 | Key2 | KValue
=====+======+=======
A | X | 100
B | Y | 200
C | X | 220
B | X | 300
B | Y | 50
可以包含以下值Key1
和['A','B','C','D']
值Key2
。
我需要SQL,它将返回所有['X','Y']
组合的矩阵及其值的总和(也是零和的组合)。因此,之前的结果应该返回:
Key1 x Key2
Key1 | Key2 | KSUM
=====+======+======
A | X | 100
A | Y | 0
B | X | 300
B | Y | 250
C | X | 220
C | Y | 0
D | X | 0
D | Y | 0
不会返回零和行!
答案 0 :(得分:1)
with
table1 ( key1 ) as (
select 'A' from dual union all
select 'B' from dual union all
select 'C' from dual union all
select 'D' from dual
),
table2 ( key2 ) as (
select 'X' from dual union all
select 'Y' from dual
),
test_data ( key1, key2, kvalue ) as (
select 'A', 'X', 100 from dual union all
select 'B', 'Y', 200 from dual union all
select 'C', 'X', 220 from dual union all
select 'B', 'X', 300 from dual union all
select 'B', 'Y', 50 from dual
)
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select t1.key1, t2.key2, nvl(ksum, 0) as ksum
from table1 t1
cross join
table2 t2
left join
( select key1, key2, sum(kvalue) as ksum
from test_data
group by key1, key2
) t3
on t1.key1 = t3.key1 and t2.key2 = t3.key2
order by key1, key2
;
<强>输出强>:
KEY1 KEY2 KSUM
---- ---- ----
A X 100
A Y 0
B X 300
B Y 250
C X 220
C Y 0
D X 0
D Y 0
答案 1 :(得分:0)
获取Key1和Key2的所有可能组合(您可以存储它们或使用笛卡尔连接生成它们),并将其连接到由Key1和Key2分组的聚合sum()查询,将空和值合并为零