简体   繁体   English

连接 2 个表,但结果中存在条件列中的所有值

[英]Join 2 tables but have all value in condition column present in result

I have 2 tables like below我有 2 张如下表

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

And I want to join them together to achive this result我想和他们一起实现这个结果

id ID score1得分1 score2得分2 score3得分3 total全部的
1 1 4 4 0 0 0 0 4 4
2 2 5 5 7 7 9 9 21 21
3 3 6 6 8 8 10 10 24 24
4 4 0 0 7 7 9 9 16 16
5 5 0 0 8 8 10 10 18 18

How ever, i have tried all join type but the id column have null values in them, can you guys show me the solution for this?如何,我已经尝试了所有连接类型,但 id 列中有空值,你们能告诉我解决方案吗? Thanks all谢谢大家

 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 - is yours first table(id,score1),CTE2 - second table(id,score2,score3) CTE - 是你的第一个表(id,score1),CTE2 - 第二个表(id,score2,score3)

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<>fiddle here db<> 在这里摆弄

You need to join in the ID.您需要加入ID。 Something like this (not tested) :像这样(未测试):

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 instead of inner join or else you would only get lignes existing in t1 LEFT JOIN 而不是内连接,否则你只会得到 t1 中存在的 lignes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL-使用联接列和条件联接2个表 - SQL - Join 2 tables using a join column AND a condition 如何在JOIN子句中为所有表测试相同的列值? - How to test the same column value for all tables in a JOIN clause? postgreSQL - 如何有条件加入 model 结果 - postgreSQL - How to have condition on Join model result 根据列条件连接不同的表 - Join different tables based on column condition 使用所有 3 个表共有的列连接 3 个表 - Join 3 tables using column common to all 3 tables 在数据库中搜索列中具有特定值的所有表 - Search a db for all tables that have a certain value in a column 查询以获取架构/数据库中具有特定列 VALUE 的所有表 - Query to fetch all tables in a Schema/DB, that have a specific column VALUE 如何计算在具有特定列的所有表中出现的值? - How to count occurrences of value in all tables that have a specific column? (SQL)从2个以上的表中选择并返回所有表,这些表具有一个公共字段,其中所有表中都存在特定值 - (SQL) Select and return all from more than 2 tables that have a common field where a specific value is present in all tables SQL&#39;LEFT JOIN&#39;两个表,每个表都有&#39;Where&#39;(不是联接条件) - Sql 'LEFT JOIN' two Tables that each Have 'Where' (not The join Condition )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM