[英]Join 2 tables but have all value in condition column present in result
I have 2 tables like below我有 2 张如下表
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?如何,我已经尝试了所有连接类型,但 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)
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.