选择语句以获取一条记录

时间:2016-04-03 08:46:18

标签: sql oracle

我的表名是SpecailUserrate包含这些记录

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

任何帮助?

2 个答案:

答案 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;

答案 1 :(得分: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的值注入子查询。