Can someone help me build a SQL query where if column1 is null/blank I should get value from column2, if column2 is also blank/null I should get value from column3.
Below is the table that I am using
Price1 Price2 Price3
120
140
160
The output that I am looking for is
Price
120
140
160
I have already tried
select Price1 as Price
from A
WHERE PRICE1 IS NOT NULL
UNION
SELECT PRICE2 as Price
from A
where PRICE1 is null
UNION
select PRICE3 as id
from A
where PRICE2 is null
select COALESCE (PRICE1,PRICE2,PRICE3) from A
select ISNULL(PRICE1,ISNULL(PRICE2,PRICE3)) from A
select
case when PRICE1 IS not null then PRICE1 when PRICE1 IS null then PRICE2 WHEN PRICE2 IS NULL then PRICE3 end PRICE id from A
None of the above syntax gets the data I'm looking for. Please help
Use COALESCE
like so:
SELECT COALESCE(Price1, Price2, Price3) FROM A;
However, this won't work if the entries are blank as opposed to NULL.
If your fields could be null or blank, you should check something like this:
select Price1 as Price
from A
WHERE PRICE1 IS NOT NULL AND PRICE1 != ''
UNION
SELECT PRICE2 as Price
from A
where PRICE1 is null OR PRICE1 = ''
UNION
select PRICE3 as id
from A
where (PRICE1 is null OR PRICE1 = '') AND (PRICE2 is null OR PRICE2 = '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With