【问题标题】:Combine two tables in SQL Server 2008 R2 based on the third tableSQL Server 2008 R2根据第三张表合并两张表
【发布时间】:2015-09-01 21:21:22
【问题描述】:

我需要在 SQL Server 2008 R2 中合并两个表。

表 1:

 id0, id1, id2, id3, value1
 100    38    89   91   23794
 120    29    60   11   98751

Tab2:

 id0, id1, id2, id3, value1
 100  78    96   30   9432

Tab3:

id1, id2, id3
 38    89   91
 78    96   30
 98    10   52
 29    60   11  

我需要在tab3的基础上合并tab1和tab2。 tab2 中的 id0 是 tab1 中 id0 的子集。

tab3 涵盖了 id1、id2 和 id3 的所有组合。

如果tab3中的组合(id1,id2 id3)在tab1或tab2中不可用,则将其添加到tab4并为value1赋值0。

如果tab2中的id0在tab1中不存在,则找出id1、id2、id3与id0的所有组合,放入到tab4中,赋值0给value1。

所以,tab4 应该是:

 id0, id1, id2, id3, value1
 100   38    89   91   23794
 100   78    96   30   9432
 100   98    10   52    0 
 100   29    60   11    0 
 120   29    60   11  98751
 120   98    10   52    0 
 120   78    96   30    0 
 120   38    89   91    0 

任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server sql-server-2008-r2


    【解决方案1】:

    你只是在寻找left join:

    select t3.*, coalesce(t1.value, t2.value, 0)
    from table3 t3 left join
         table1 t1
         on t1.id1 = t3.id1 and t1.id2 = t3.id2 and t1.id3 = t3.id3 left join
         table1 t2
         on t2.id1 = t3.id1 and t2.id2 = t3.id2 and t2.id3 = t3.id3 ;
    

    如果 id 的组合可以在 table1 或 table2 或它们之间重复,那么您可能还需要聚合。但你的问题表明这不是问题。

    编辑:

    编辑后的问题看起来有点不同,但我认为你想要:

    select id0.id0, t3.id1, t3.id2, t3.id3,
           coalesce(t1.value, t2.value, 0)
    from table3 t3 cross join
         (select id0 from table1 union select id0 from table2) id0 left join
         table1 t1
         on t1.id0 = id0.id0 and t1.id1 = t3.id1 and t1.id2 = t3.id2 and t1.id3 = t3.id3 left join
         table1 t2
         on t2.id0 = id0.id0 and t2.id1 = t3.id1 and t2.id2 = t3.id2 and t2.id3 = t3.id3 ;
    

    这会使用cross join 生成所有组合,然后从其中一个表中填充值字段。

    【讨论】:

    • @user3601704 。 . .它由子查询定义。
    【解决方案2】:

    所以 LEFT JOIN 两个表到 Tab3,并从两者中添加 value1:

    SELECT t3.id1, t3.id2, t3.id3, IFNULL(t1.value1+t2.value1, 0) AS value1
    FROM Tab3 t3 LEFT JOIN Tab1 t1
      ON t3.id1 == t1.id1 AND t3.id2 == t1.id2 AND t3.id3 == t1.id3 LEFT JOIN Tab2 t2
      ON t3.id1 == t2.id1 AND t3.id2 == t2.id2 AND t3.id3 == t2.id3
    

    【讨论】:

    • 不要那样做。如果你的问题是错误的,不要让人们浪费时间回答你的问题。花点时间问一个正确的问题。一旦你问了一些问题,如果你得到答案,接受并根据你问的内容投票,而不是你没有问的内容。如果您以后决定要问一个不同的问题,也可以这样做。
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2016-01-16
    相关资源
    最近更新 更多