2016-04-03 60 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到子查询。

相关问题