比较两个表并找到缺失的组合

时间:2018-08-27 18:14:21

标签: sql postgresql

我的主表中有3列。

  1. 得分(0-99,100-110)
  2. 评分(5-9,10-15)
  3. 位置(A,B)

我拥有所有这些组合(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

1 个答案:

答案 0 :(得分:2)

您可以尝试使用if(map.containsKey("name") && map.containsKey("age")) { // do something String name = map.get("name"); String age = map.get("age"); ... 来为CROSS JOINscorerate列生成笛卡尔乘积,形成完整表。

然后根据location表进行OUTER JOIN

CROSS JOIN

查询1

create table t(
  score varchar(50),
  rate varchar(50),
  location  varchar(50),
  value  int
);

insert into t values ('0-99','5-9','A',2);   
insert into t values ('0-99','10-15','A',3);
insert into t values ('100-110','10-15','A',6);
insert into t values ('100-110','5-9','B',7);
insert into t values ('0-99','10-15','B',1);

Results

SELECT  
  s.score,
  r.rate,
  l.location,
  coalesce(t1.value,0)
FROM 
(SELECT DISTINCT score FROM T) s
CROSS JOIN
(SELECT DISTINCT rate FROM T) r
CROSS JOIN
(SELECT DISTINCT location FROM T) l
LEFT JOIN t t1 on s.score = t1.score and t1.rate = r.rate and t1.location = l.location
ORDER BY  l.location