2016-04-03 89 views
-1

我有表名是SpecailUserrate包含這些記錄Select語句來獲得一個記錄

USER_ID NAME FromCountry ToCountry Rate 
----------------------------------------------  
1   xyz  null   null  0.75 
1   xyz  1   null  0.80 
1   xyz  null   2  0.81 

我需要的SQL語句返回1個記錄

example user 1 want to use special rate depend on FromCountry or ToCountry 

如果從國家1用戶1具有特殊的利率將使用0.80 如果不會使用默認利率0.75

任何幫助嗎?

+1

分享你試過的東西嗎? – Sanj

+0

你想要什麼(變量)匹配FromCountry/ToCountry? –

+0

用戶輸入變量 –

回答

0

我正確地得到了問題。但我猜想解決方案的關鍵是使用EXISTS

的東西,看起來像這樣

select * from country where FromCountry=1 
union 
select * from country where not exists(select * from where FromCountry=1) and ToCountry=2 
union 
select * from country where not exists(select * from where FromCountry=1 or ToCountry=2) and FromCountry is NULL; 
0

這裏是提供答案的一種方法:

select coalesce(c1.rate, def.rate) as rate 
from 
    (select user_id, rate 
     from Special_User_rate 
     where fromcountry is null and tocountry is null) def 
    left join 
     (select user_id, rate 
      from Special_User_rate 
      where fromcountry = 1) c1 
    on def.user_id = c1.user_id 
/

這是不理想的,因爲它很難注入值fromcountry到子查詢。

相關問題