【问题标题】:Ensure percentages are between 0 and 1, inclusive (using a single function)确保百分比介于 0 和 1 之间(使用单个函数)
【发布时间】:2018-07-24 05:43:27
【问题描述】:

我在condition 表中有百分比:

create table condition (percent_decimal number(3,2));
insert into condition values (-0.01);
insert into condition values (0.1);
insert into condition values (1);
insert into condition values (1.1);
commit;

PERCENT_DECIMAL
---------------
          -0.01
             .1
              1
            1.1

我想选择这些值,但修改它们以将它们显示为 0 和 1(含)之间的百分比:

  • -0.01 转换为0
  • 保持 .1 不变
  • 保持 1 不变
  • 1.1 转换为1

我可以使用greatestleast 函数成功地做到这一点:

select
    percent_decimal,
    least(1,greatest(0,percent_decimal)) as percent_modified
from
    condition

PERCENT_DECIMAL PERCENT_MODIFIED
--------------- ----------------
          -0.01                0
             .1               .1
              1                1
            1.1                1

但是,我想知道是否有更简洁的方法来做到这一点 - 使用单个函数。

【问题讨论】:

  • 或许可以考虑另一种方法 - 首先使用检查约束 alter table condition add constraint chk check ( percent_decimal between 0 and 1) 或类似的方式阻止数据进入那里

标签: sql oracle math select oracle12c


【解决方案1】:

您可以使用单例表达式:

select
    percent_decimal,
    case when percent_decimal < 0 then 0
         when percent_decimal > 1 then 1
         else percent_decimal
    end as percent_modified
from
    condition
/

PERCENT_DECIMAL PERCENT_MODIFIED
--------------- ----------------
          -0.01                0
             .1               .1
              1                1
            1.1                1

它更长,但不使用任何函数,我认为稍后出现的人会更清楚你的逻辑是什么。

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2015-02-20
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    相关资源
    最近更新 更多