简体   繁体   中英

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

I have 2 tables like below

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

And I want to join them together to achive this result

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

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? 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)

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

You need to join in the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM