开发者

Return one of two columns in a view - whichever one is not null

I have a table with three columns:

ColumnA          ColumnB         ColumnC
AAA               NULL            123
BBB               222             NULL
CCC               NULL            NULL

I would like to create a SELECT statement which will return ColumnA, and then a second column which will either show the value of ColumnB unless ColumnB is null; otherwise it will show the value of ColumnC, even it it's NULL. Can I use an IF statement for that? Something like:

SELECT ColumnA, 
IF(ColumnB IS NULL, ColumnC, ColumnB)
FROM tab开发者_开发问答le

**If I get this working, the next step would be to return the value of a joined column instead of ColumnB. In effect the IF statement would be

IF(table.ColumnB IS NULL, table.ColumnC, table2.ColumnD)


Use COALESCE

SELECT ColumnA, COALESCE(ColumnB, ColumnC) as 'Value'


Reading to the end of your question it sounds like you need to use CASE

CASE WHEN table.ColumnB IS NULL 
     THEN table.ColumnC 
     ELSE table2.ColumnD 
END AS Whatever
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜