Sql范围查询

时间:2016-01-14 07:28:06

标签: sql oracle

查询从表TBL_CHARGES返回2个值:

Range_in_hrs    Range_to_hours   charges
       4             48            5
      48             70           10
      70             90           20

如果通过范围47.59,则从表格中选择费用,退货费用应为5.如果通过48.00,则费用为5。 如果通过48.01,则费用应为10。

我正在尝试这个

SELECT * 
FROM TBL_CHARGES
WHERE 48.00 between Range_in_hrs and Range_to_hours

但它不起作用。

3 个答案:

答案 0 :(得分:1)

听起来你需要避免使用BETWEEN而是使用显式范围,如下所示:

select * 
from   tbl_charges
where  48 > range_in_hrs
and    48 <= range_to_hours;

这是一个示例,显示了您可能获得的各种不同值的输出:

with tbl_charges as (select 4 range_in_hours, 48 range_to_hours, 5 charges from dual union all
                     select 48 range_in_hours, 70 range_to_hours, 10 charges from dual union all
                     select 70 range_in_hours, 90 range_to_hours, 20 charges from dual),
            vals as (select 4 val from dual union all
                     select 4.01 val from dual union all
                     select 47.59 val from dual union all
                     select 48 val from dual union all
                     select 48.01 val from dual union all
                     select 70 val from dual union all
                     select 71 val from dual)
select vals.val,
       tc.charges
from   vals
       left outer join tbl_charges tc on (vals.val > tc.range_in_hours and vals.val <= tc.range_to_hours);

       VAL    CHARGES
---------- ----------
         4           
      4.01          5
     47.59          5
        48          5
     48.01         10
        70         10
        71         20

答案 1 :(得分:0)

SELECT charges 
FROM TBL_CHARGES
WHERE ceil(to_number('48.01')) between Range_in_hrs and Range_to_hours

使用Replace和Ceil。

答案 2 :(得分:0)

这个问题解决了我的问题。

SELECT * 来自TBL_CHARGES 在Range_in_hrs ||'。01'和Range_to_hours ||'。00'之间的48.00