使用条件连接显示来自 3 个表的数据

display data from 3 tables with conditional joining

我有 3 个表格,格式如下。

Table A                    Table B                   Table C   
id                         id1  id2                   id   name
1                          1    null                  1.1  john   
2                          1    1.1                   
                           2    null                  

随查询

select a.id,b.id1,b.id2,c.id,c.name 
from TableA a 
join TableB b on a.id = b.id1
left join TableC on b.id2 = c.id

我会看到下面的数据

a.id  b.id1  b.id2  c.id  c.name
1     1      null   null  null
1     1      1.1    1.1   john
2     2      null   null  null

我的意图是,我需要去掉结果集中的第一行,即如果有数据则只显示非空行如果没有数据则显示空行。

如果您需要任何说明,请告诉我。

如果我没理解错的话,这里有一个使用 rank 的选项:

select *
from (
    select a.id,b.id1,b.id2,c.id,c.name,
        rank() over (partition by b.id1 
                       order by case when b.id2 is null then 1 else 0 end) rnk
    from TableA a 
        join TableB b on a.id = b.id1
        left join TableC on b.id2 = c.id
) t
where id2 is not null or rnk = 1

您的重复项都来自 TableB。您可以通过多种方式确定这些行的优先级。我认为您的数据最简单的方法是聚合:

select a.id, b.id1, b.id2, c.id, c.name 
from TableA a join
     (select b.id1, max(b.id2) as id2
      from TableB b
      group by b.id1
     ) b
     on a.id = b.id1 left join
     TableC
     on b.id2 = c.id;

我们可以通过使用另一个 table 来解决,如果 Tableb 中的 id1id2 上至少有一个非空值,并且如果所以当有空值时删除。

这个 table 将是:

select sum(case when id2 is null then 0 else 1 end) as test,
id1
from TableB
group by id1

查询:

select a.id,b.id1,b.id2,c.id,c.name 
from TableA a 
join TableB b on a.id = b.id1
left join TableC on b.id2 = c.id
left join (
select sum(case when id2 is null then 0 else 1 end) as test,
id1
from TableB
group by id1
) AS Table_test on Table_test.id1 = b.id1

where b.id2 is not null or Table_test.test = 0

因此,在有多行的情况下,所有 id2 都在一行中,没有空行,并且在只有空行的情况下,您将保留空行。