我有两个以下格式的表:
data_1 | data_2 | weight
1 | a | 25
1 | b | 25
1 | c | 25
1 | d | 25
2 | e | 100
data_4 | data_1 | data_2 | value
AB | 1 | a | 25
AB | 1 | b | 25
AB | 1 | c | 25
AB | 1 | d | 25
BC | 2 | e | 50
BC | 2 | f | 50
CD | 1 | a | 50
CD | 1 | b | 50
我正在寻找创建以下输出:
data_4 | data_1 | data_2 | value | weight
AB | 1 | a | 25 | 25
AB | 1 | b | 25 | 25
AB | 1 | c | 25 | 25
AB | 1 | d | 25 | 25
BC | 2 | e | 50 | 100
BC | 2 | f | 50 | 0
CD | 1 | a | 50 | 25
CD | 1 | b | 50 | 25
CD | 1 | c | 0 | 25
CD | 1 | d | 0 | 25
本质上,我希望将data_1和data_2上的表与每个data_4记录连接起来,同时显示值和权重及其对应的值。
我尝试了几件事,但似乎没有获得正确的输出。任何帮助将非常感激。
如果我理解正确,这是相当复杂的。 (在我看来,最困难的部分是在第一列中获得正确的data_4
- full join
会产生null
值。
以下方法从table_2
中获取所有行,并使用table_1
匹配到left join
。然后,在其余行中添加left join
不包括的行:
select t2.data_4, t2.data_1, t2.data_2, t2.value, coalesce(t1.weight, 0) as weight
from table2 t2 left join
table1 t1
using (data_1, data_2)
union all
select t2.data_4, t1.data_1, t1.data_2, t2.value, t1.weight
from table_1 t1 cross join
(select distinct t2.data_4 from table2 t2) d4 left join
table_2 t2
on t2.data_4 = d4.data_4 and
t2.data_1 = t1.data_1 and
t2.data_2 = t1.data_2
where t2.data_4 is null;
编辑:
嗯。 。 。我认为可能有一种更简单的方法:
select t41.data_4, t41.data_1, t2.data_2,
coalesce(t2.value, 0) as value,
coalesce(t1.weight, 0) as weight
from (select distinct t2.data_4, t2.data_1 from table_2) d41 left join
table_1 t1
on t1.data_1 = t41.data_1 left join
table_2 t2
on t2.data_4 = t41.data_4 and
t2.data_1 = t41.data_1 and
(t2.data_2 = t1.data_2 or t1.data_1 is null);
如果我理解正确,这是相当复杂的。 (在我看来,最困难的部分是在第一列中获得正确的data_4
- full join
会产生null
值。
以下方法从table_2
中获取所有行,并使用table_1
匹配到left join
。然后,在其余行中添加left join
不包括的行:
select t2.data_4, t2.data_1, t2.data_2, t2.value, coalesce(t1.weight, 0) as weight
from table2 t2 left join
table1 t1
using (data_1, data_2)
union all
select t2.data_4, t1.data_1, t1.data_2, t2.value, t1.weight
from table_1 t1 cross join
(select distinct t2.data_4 from table2 t2) d4 left join
table_2 t2
on t2.data_4 = dr.data_4 and
t2.data_1 = t1.data_1 and
t2.data_2 = t1.data_2
where t2.data_4 is null;