有人可以帮我构建一个SQL查询,如果column1为null / blank我应该从column2获取值,如果column2也是空/ null我应该从column3获取值。
以下是我正在使用的表格
Price1 Price2 Price3
120
140
160
我正在寻找的输出是
Price
120
140
160
我已经尝试了
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
以上语法都没有获取我正在寻找的数据。请帮忙
答案 0 :(得分:4)
像这样使用COALESCE
:
SELECT COALESCE(Price1, Price2, Price3) FROM A;
但是,如果条目为空而不是NULL,则不起作用。
答案 1 :(得分:1)
如果您的字段可能为空或空白,则应检查以下内容:
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 = '')
答案 2 :(得分:0)
如果您认为自己有空字符串,可以尝试:
select
case when coalesce(PRICE1, '') <> '' then PRICE1
when coalesce(PRICE2, '') <> '' then PRICE2
when coalesce(PRICE3, '') <> '' then PRICE3
end AS PRICE
FROM A
答案 3 :(得分:0)
如果在第一个col中为null,则查看第二个,如果为null则在第三个col中查找。
select isnull(PRICE1,isnull(PRICE2,PRICE3)) as Price from A