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

大城市里の小女人 提交于 2020-01-02 04:48:05

问题


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 table

**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)

回答1:


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



回答2:


Use COALESCE

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



来源:https://stackoverflow.com/questions/5199360/return-one-of-two-columns-in-a-view-whichever-one-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!