2017-09-22 67 views
-1

我需要在我的查詢中某個where子句僅在某些情況下進行評估。SQL只評估某些情況某些情況下db2和sybase

例如,

select * from employee e where e.age=14 and e.salary=1000 

在上述查詢我需要薪水其中當e.age > 30

我使用DB2和SYBASE僅被評估子句。

+0

'選擇從員工的E *其中e.age = 14,e.salary = 1000和e.age> 30;' – SriniV

回答

0

使用OR如果你想添加的條件查詢,不應該總是適用,就像這樣:

SELECT * 
FROM employee e 
WHERE e.age = 14 OR (e.age>30 AND e.salary=1000) 

這會給你e.age = 14所有結果不管什麼工資及一切結果e.age>30其中,工資是1000

+0

不是真的,這裏是需要的 – user2713255

+0

@ user2713255我更新了我的答案。 – waka

0

做這個

Select * from employee e where e.age=14 or e.age>30 and e.salary=1000 
0

如何:

select * 
from employee e 
where e.age = 14 -- change to any age you want, then ... 

and (-- if age > 30 then we also need to check salary 
     (e.age > 30 and e.salary = 1000) 
     or 
     -- if age <= 30 then we don't care about salary 
     (e.age <= 30) 
    ) 

的關鍵是具有互補的where條款覆蓋表中的所有行(e.age > 30e.age <= 30)。


另一種可能性(應Sybase ASE的工作,不知道DB2語法)...

select * 
from employee e 
where e.age = 14 -- change to any age you want, then ... 

and e.salary = case when e.age > 30 
         then 1000  -- when e.age > 30, e.salary=1000 
         else e.salary -- when e.age <= 30, e.salary=e.salary 
        end