2015-05-29 80 views
2

有人可以帮我建立一个SQL查询,如果column1为空/空白我应该从column2得到值,如果column2也是空白/ null我应该从column3得到值。如果第一列在SQL(MS SQL)中为空白/空,如何从第二列中选择值?

下面是我使用

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

是那些空白或空白。如果它们是空值,那么聚结应该起作用......如果它们是空白的,它们就不会。尝试更改case语句以将“IS NOT NULL”替换为“<>”'“”,如果解决该问题,则空白不是空值。 –

+0

有任何回答有用吗? – Simone

回答

0

如果你认为你有空字符串,你可以尝试:

select 
    case when coalesce(PRICE1, '') <> '' then PRICE1 
     when coalesce(PRICE2, '') <> '' then PRICE2 
     when coalesce(PRICE3, '') <> '' then PRICE3 
    end AS PRICE 
FROM A 
+0

谢谢Forgues,这回答我的关注。 – Prav

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 = '') 
4

使用COALESCE像这样:

SELECT COALESCE(Price1, Price2, Price3) FROM A; 

然而,这不会如果工作条目是空的而不是NULL。

0

简单,如果空在第一关口,看在第二,如果这是在第三栏为空的样子。

select isnull(PRICE1,isnull(PRICE2,PRICE3)) as Price from A 
相关问题