【问题标题】:Join 2 tables but have all value in condition column present in result加入 2 个表,但结果中存在条件列中的所有值
【发布时间】:2021-07-30 14:09:25
【问题描述】:

我有 2 个如下表

id score1
1 4
2 5
3 6
id score2 score3
2 7 9
3 8 10
4 7 9
5 8 10

我想把他们联合起来实现这个结果

id score1 score2 score3 total
1 4 0 0 4
2 5 7 9 21
3 6 8 10 24
4 0 7 9 16
5 0 8 10 18

但是,我已经尝试了所有连接类型,但 id 列中包含空值,你们能告诉我解决方案吗?谢谢大家

【问题讨论】:

  • 我删除了不一致的标签,请只标记您正在使用的数据库

标签: sql


【解决方案1】:
select 
   coalesce(t1.id,t2.id) id
 , coalesce(t1.score1,0) score1
 , coalesce(t2.score2,0) score2
 , coalesce(t2.score3,0) score3
 , coalesce(t1.score1,0) + coalesce(t2.score2,0) + coalesce(t2.score3,0) total
from table1 t1
full outer join table2 t2 
 on t1.id = t2.id 

db小提琴here

【讨论】:

    【解决方案2】:
     SELECT COALESCE(C.ID,C2.ID)ID,COALESCE(C.SCORE1,0)SCORE1,
     COALESCE(C2.SCORE2,0)SCORE2,COALESCE(C2.SCORE3,0)SCORE3,
     COALESCE(C.SCORE1,0)+COALESCE(C2.SCORE2,0)+COALESCE(C2.SCORE3,0) TOTAL
     FROM CTE AS C
     FULL JOIN CTE2 C2 ON C.ID=C2.ID
     ORDER BY ID
    

    CTE - 是你的第一个表(id,score1),CTE2 - 第二个表(id,score2,score3)

    【讨论】:

      【解决方案3】:

      您需要加入ID。 像这样的东西(未经测试):

      SELECT
          t1.id,
          ISNULL(t1.score1, 0)
          ISNULL(t2.score2, 0)
          ISNULL(t2.score3, 0)
      FROM table1 t1
      LEFT JOIN table2 t2 ON t1.id = t2.id
      

      LEFT JOIN 而不是内部连接,否则你只会得到 t1 中存在的 lignes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-19
        • 2017-01-16
        • 1970-01-01
        • 2015-08-13
        • 2013-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多