2015-05-29 51 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 
相關問題