2013-07-29 20 views
1

我有表字段update_它可以有空,一些價值版本具有null以及價值得到值..如何從數據庫中單個查詢

Select * from Employee where employee_id = '1234' and updated_version is null 

Select * from Employee where employee_id = '1234' and updated_version ='1' 

我要兩個查詢組合

我已經嘗試過,但沒有工作。

Select * from Employee 
where employee_id = '1234' 
and updated_version = (select case when updated_version is null 
           then NULL 
           else updated_version 
           end) 

注:我西港島線得到員工ID和updated_version輸入來自其他表

很抱歉的混亂。更新後的版本值不僅爲1,並且爲空。它可以是我從另一張桌子上得到的任何值。所以,我從其他表獲得什麼價值,我必須用Employee表中的條件查詢,以獲得適當的結果。並非全部結果。

+1

你試過Parado說的嗎? –

+1

顯示您的輸出表結構。 –

回答

1

試試這個方法:

Select * from Employee 
where employee_id = '1234' 
and (updated_version is null or updated_version='1') 

編輯:

Select * 
from Employee e 
left join other_table ot on ot.employee_id = e.employee_id 
         and ot.updated_version =e.updated_version 
+0

如果我必須pull update_version ='1',我將得到兩個記錄都爲空以及版本爲1.我應該只有1條記錄版本爲1 :( –

+0

該值將來自其他表。如果一個員工有多個updated_version,我們會得到最後一個版本,如果不是,我們會收到它爲null –

+0

@muthukumar嘗試新的解決方案,我已經添加請 – Parado

1

嘗試此查詢出來:

Select * from Employee where employee_id = '1234' and (updated_version ='1' OR updated_version is null) 

編輯:試試這個(未測試)!

Select * from Employee where employee_id = '1234' and 
CASE updated_version 
WHEN '1' THEN '1' 
WHEN Null THEN Null 
ELSE updated_Version 
END 
+0

正如我所說,如果udpated_version爲1,它將返回2行。我應該只獲得一行版本= 1。 –

+1

@muthukumar顯示您的輸出表結構 –

+0

是的,把你期望使用的所有東西放到你的原來的問題。另外,請嘗試新的查詢。 – Elias

2

正如其他人所說,有點不清楚你想要在輸出什麼,但如果我讓你正確的,你想有一個「updated_version」填充了行與空值的「updated_version」行?意思是,你想要最「最近」的更新版本? (假設給定employee_id的表中會有許多版本/行​​)。

嘗試(未經測試):

select * from (
    select e.*, row_number() over (partition by employee_id order by updated_version desc nulls last) rnum 
    from employee e 
    where employee_id = '1234' 
) 
where rnum = 1; 

通過並不是必需的,你正在尋找的只是1 EMPLOYEE_ID,但仍需要如果要將此擴展到多個員工ID的分區。