SQL:根据返回的数据在查询结果中添加行

时间:2011-06-16 08:57:07

标签: sql

对不起标题,不容易正确地说出来。

我有一张表A,它有一个可能的值范围的商业密钥(Akey):k1,k2和k3

AKey ACol2  ACol3
k1   val12  val13
k2   val22  val23
k3   val32  val33

我有一张表B,其中包含

等条目
BKey1 BKey2 BKey3  AKey Col5  Col6
kk11  kk12  kk13   k1   val15 val16
kk21  kk22  kk23   k3   val25 val26

BKey1,BKey2和Bkey3是表B的业务密钥 Akey是表A的外键

我想生成一个结果集,其中表B与表A(在AKey上)连接,但是对于表A中的非引用键,包括“空”行(对于表B的每个键,这包括这个)。在我想要的例子中:

BKey1 BKey2 BKey3  AKey Col5  Col6   ACol2 ACol3
kk11  kk12  kk13   k1   val15 val16  val12 val13
kk21  kk22  kk23   k3   val25 val26  val32 val33
kk11  kk12  kk13   k2   def   def    val22 val23
kk11  kk12  kk13   k3   def   def    val32 val33
kk21  kk22  kk23   k1   def   def    val12 val13
kk21  kk22  kk23   k2   def   def    val22 val23

我有两个条目,就像A(k1,k2和k3)的所有其他键范围值的内部连接+条目一样,具有B的列的默认值(我需要设置)。我尝试了一个右连接但是我在结果中只有一次默认条目而不是B的每个键。你能帮我找到正确的方向吗?

Christian

1 个答案:

答案 0 :(得分:2)

select D.BKey1,
       D.BKey2,
       D.BKey3,
       D.AKey,
       coalesce(B.Col5, 'def') as Col5,
       coalesce(B.Col6, 'def') as Col6,
       A.ACol2,
       A.ACol3
from (select B.BKey1, B.BKey2, B.BKey3, A.AKey
      from TableA as A
        cross join (select distinct BKey1, BKey2, BKey3
                    from TableB
                   ) as B
     ) as D
  inner join TableA as A
    on A.AKey = D.AKey
  left outer join TableB as B
    on B.BKey1 = D.BKey1 and 
       B.BKey2 = D.BKey2 and 
       B.BKey3 = D.BKey3 and 
       B.AKey = D.AKey

进行测试:

with TableA(AKey, ACol2,  ACol3) as
(
select 'k1',   'val12',  'val13' union all
select 'k2',   'val22',  'val23' union all
select 'k3',   'val32',  'val33'
),
TableB(BKey1, BKey2, BKey3,  AKey, Col5,  Col6) as
(
select 'kk11',  'kk12',  'kk13',   'k1',   'val15', 'val16' union all
select 'kk11',  'kk12',  'kk13',   'k2',   'valx',  'valy'  union all
select 'kk21',  'kk22',  'kk23',   'k3',   'val25', 'val26'
)

select D.BKey1,
       D.BKey2,
       D.BKey3,
       D.AKey,
       coalesce(B.Col5, 'def') as Col5,
       coalesce(B.Col6, 'def') as Col6,
       A.ACol2,
       A.ACol3
from (select B.BKey1, B.BKey2, B.BKey3, A.AKey
      from TableA as A
        cross join (select distinct BKey1, BKey2, BKey3
                    from TableB
                   ) as B
     ) as D
  inner join TableA as A
    on A.AKey = D.AKey
  left outer join TableB as B
    on B.BKey1 = D.BKey1 and 
       B.BKey2 = D.BKey2 and 
       B.BKey3 = D.BKey3 and 
       B.AKey = D.AKey

结果:

BKey1 BKey2 BKey3 AKey Col5  Col6  ACol2 ACol3
----- ----- ----- ---- ----- ----- ----- -----
kk11  kk12  kk13  k1   val15 val16 val12 val13
kk11  kk12  kk13  k2   valx  valy  val22 val23
kk11  kk12  kk13  k3   def   def   val32 val33
kk21  kk22  kk23  k1   def   def   val12 val13
kk21  kk22  kk23  k2   def   def   val22 val23
kk21  kk22  kk23  k3   val25 val26 val32 val33

测试here