我想获取一列的值(如果存在),如果该列中没有值,则将其留空
Table 1 (Student):
id Name dateofbirth
1 John 16-09-2015
2 Mark 25-08-2016
3 Matt 20-08-2017
4 Peter 16-08-2014
Table 2 (Relationship):
id StudentID NextOfKin Relationship Active
1 1 David Mother Y
2 2 Frank Father N
3 3 Jacob Mother Y
4 3 Park Mother N
SELECT a.Name, a.dateofbirth, b.NextOfKin
FROM dbo.Student a
LEFT OUTER JOIN dbo.Relationship b
ON a.id = b.StudentID
WHERE b.Relationship = 'Mother'
AND b.Active = 'Y'
如果b.NextOfKin有一个值,请输入类似的值,否则将其留空。请您指教
在上述情况下,彼得没有近亲,马克没有母亲。我仍然希望显示他的名字,但如果没有母亲,则应该为空白
答案 0 :(得分:0)
您可以coalesce()
函数并将所有其他条件放在ON Clause
中,而不是Where Clause
SELECT a.Name, a.dateofbirth, coalesce(b.NextOfKin,'') as NextOfKin
FROM dbo.Student a
LEFT OUTER JOIN dbo.Relationship b
ON a.id = b.StudentID
and b.Relationship = 'Mother'
AND b.Active = 'Y'