问题
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