How to get all distinct id from two tables after join?

时间:2016-04-12 00:34:11

标签: sql sql-server

I want to get all distinct value from two tables after join. Tow tables are.. Table: Student

Roll    Name
1       Anis
2       Badol
3       Chaity

Table:Exam

Roll    Quiz    Mid Final
1        15     20  40
3        25     20  42
4        10     12  8

I want to get that output

Roll    Name    Mark
3      Chaity   87
1       Anis    75
4      Unknown  30
2      Badol    0

where name in null that replaced by 'Unknoun' and mark is null that replaced by '0'

I tried this code

select s.roll, name, (quiz+mid+final) as Mark
from student s
full outer join exam e on
s.roll=e.roll

and get that output..

roll   name    mark
1      anis     75
2      badol    NULL
3     chaity    87
NULL    NULL    30

(sorry for the bad English)

1 个答案:

答案 0 :(得分:1)

One method uses full outer join and coalesce():

select coalesce(t1.roll, t2.roll) as roll,
       coalesce(t1.name, 'Unknown') as name,
       (coalesce(quiz, 0) + coalesce(mid, 0) + coalesce(final, 0)) as mark
from t1 full outer join
     t2
     on t1.roll = t2.roll
order by mark desc;
相关问题