避免Coalesce中的Null值

时间:2017-06-01 02:40:56

标签: sql

我使用coalesce来生成结果,但是获得了具有Null值的重复行。

示例表格如下:

Table - Student             
ID  Student Subject id  Subject   Grade id
100 Peter   200         Chinese   201
101 Mary    300         English   302
102 Sam     400         Maths     403
103 John    900         Music   

Chinese Table       
Subject id  Grade id    Grade
200         201         Good
200         202         Average
200         203         Poor

English Table       
Subject id  Grade id    Grade
300         301         Good
300         302         Average
300         303         Poor

Maths Table     
Subject id  Grade id    Grade
400         401         Good
400         402         Average
400         403         Poor

Select Id, Name, 
Coalesce (chinese.grade, english.grade, maths.grade) 
from Student 
Left join Chinese On student.id = Chinese.subjectId AND student.gradeId = Chinese.gradeId
Left join English On student.id = English.subjectId AND student.gradeId = Enlgish.gradeId
Left join Maths On student.id = Maths.subjectId AND student.gradeId = Maths.gradeId

Result
ID  Student Subject     Grade 
100 Peter   Chinese         Good
100 Peter   Chinese         NULL
101 Mary    English         Average
101 Mary    English         NULL
102 Sam     Maths           Poor
102 Sam     Maths           NULL
103 John    Music           NULL

我不确定Null值的重复行来自何处​​,只是想知道如何通过使用coalesce来避免给出null值?

2 个答案:

答案 0 :(得分:0)

使用:

select s.id,s.name,s.[subject],
coalesce(coalesce(coalesce(c.grade,e.grade,c.grade),e.grade, coalesce(c.grade,e.grade,c.grade)),m.grade,coalesce(coalesce(c.grade,e.grade,c.grade),e.grade, coalesce(c.grade,e.grade,c.grade))) as grade
from student s
left join chinese c on s.subjectid = c.subjectid and c.gradeid = s.gradeid
left join english e on e.subjectid = s.subjectid and e.gradeid = s.gradeid
left join maths m on m.subjectid = s.subjectid and m.gradeid = s.gradeid

结果

id--name----subject--grade

100 Peter   Chinese Good
101 Mary    English Average
102 Sam     Maths   Poor
103 John    Music   NULL

答案 1 :(得分:0)

回答“只是想知道如何通过使用coalesce避免给出空值?”只是问题的一部分,因为重复记录的来源需要的信息比提供的更多:

COALESCE返回其参数列表中的第一个非空值,如果所有参数都是NULL,则返回NULL

如果所有Select Id, Name, Coalesce (chinesetable.grade, englishtable.grade, mathstable.grade) ...NULLchinesetable.grade都是englishtable.grade,那么mathstable.grade仍会为您提供NULL成绩。你需要决定在那种情况下你想做什么。你可以跳过这些行:

Select * From
    (Select Id, Name, Coalesce (chinesetable.grade, englishtable.grade, mathstable.grade) As Grade from Student where id = id...) As grades_with_nulls
    Where Grade Is Not Null;

或者提供默认值作为Coalesce的最后一个参数:

Select Id, Name, Coalesce (chinesetable.grade, englishtable.grade, mathstable.grade, 'None') from Student where id = id...