我的主表中有3列。
我拥有所有这些组合(2 * 2 * 2 = 8个组合)
下面是我的主表中的组合
score rate location
----------------------------
0-99 5-9 A
100-110 5-9 A
0-99 10-15 A
100-110 10-15 A
0-99 5-9 B
100-110 5-9 B
0-99 10-15 B
100-110 10-15 B
我还有另一个包含实际数据的表。我想找出实际表中所有缺少的组合。如何找到那些缺失的组合并追加到该列中值为“ 0”的实际表中?
实际数据
score rate location value
---------------------------------
0-99 10-15 A 3
100-110 10-15 A 6
0-99 10-15 B 1
预期输出
score rate location value
------------------------------------
0-99 5-9 A 0
0-99 10-15 A 3
100-110 10-15 A 6
100-110 5-9 B 0
0-99 10-15 B 1
100-110 5-9 A 0
100-110 10-15 B 0
0-99 10-15 B 0
答案 0 :(得分:1)
根据您的实际数据和预期结果,score
,rate
,location
列的值似乎是固定的,因此您可以使用UNION ALL
来让score
, rate
,location
是表格。
CROSS JOIN
为score
,rate
,location
联合表生成笛卡尔乘积,制成完整表。
然后OUTER JOIN
create table t(
score varchar(50),
rate varchar(50),
location varchar(50),
value int
);
insert into t values ('0-99','10-15','A',3);
insert into t values ('100-110','10-15','A',6);
insert into t values ('0-99','10-15','B',1);
查询1 :
SELECT
s.score,
r.rate,
l.location,
coalesce(t1.value,0)
FROM
(
SELECT '0-99' score
UNION ALL
SELECT '100-110'
) s
CROSS JOIN
(
SELECT '10-15' rate
UNION ALL
SELECT '5-9'
) r
CROSS JOIN
(
SELECT 'A' as "location"
UNION ALL
SELECT 'B'
) l
LEFT JOIN t t1 on s.score = t1.score and t1.rate = r.rate and t1.location = l.location
ORDER BY l.location
Results :
| score | rate | location | coalesce |
|---------|-------|----------|----------|
| 0-99 | 10-15 | A | 3 |
| 0-99 | 5-9 | A | 0 |
| 100-110 | 10-15 | A | 6 |
| 100-110 | 5-9 | A | 0 |
| 100-110 | 5-9 | B | 0 |
| 0-99 | 10-15 | B | 1 |
| 100-110 | 10-15 | B | 0 |
| 0-99 | 5-9 | B | 0 |
答案 1 :(得分:0)
对maintable和Actualtable使用左联接,然后对value列应用案例
select t.score,t.rate,t.location, case when value is null then 0 else value end as value
from t left join t1
on t.score=t1.score and t.rate=t1.rate
and t.location=t1.location