Oracle

確保百分比介於 0 和 1 之間(使用單個函式)

  • February 13, 2018

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.010
  • 保持.1原樣
  • 保持1原樣
  • 轉換1.11

我可以使用最大最小功能成功地做到這一點:

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

但是,我想知道是否有更簡潔的方法來做到這一點 - 使用單個函式。

我經常對 DBA-SE 成員提出的巧妙技術感到驚喜。當我認為我已經想出了做某事的最簡單方法時,有人想出了更簡單的方法。

好的,這不是一個嚴肅的問題,讓我想起了https://codegolf.stackexchange.com/

我可以做得更好,根本沒有功能。

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

但是我們需要一個函式。最後,Oracle 12.2 允許長(128 字節)標識符,因此我們可以給出更有意義的名稱:

with function 
 "Convert -0.01 to 0, Leave .1 as is, Leave 1 as is, Convert 1.1 to 1" (p number)
return number
as
begin
 if (p = -0.01) then return 0; end if;
 if (p = 1.1) then return 1; end if;
 return p;
end;
select
 percent_decimal,
 "Convert -0.01 to 0, Leave .1 as is, Leave 1 as is, Convert 1.1 to 1"(percent_decimal) 
   as percent_modified
from condition;

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

我還碰巧有一個超級秘密功能,恰好可以滿足您的需求:

create or replace function "." wrapped
a000000
1
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
8
97 aa
30RI5qP/Li6VhppxgO2AXQw62mYwg1xfrZ6pfI6iO8cYr/L9s3tguDonZ52omRm1G6sfUCen
xkcEU/4jCxrp7Ii4VNrCrVY6cDr0UNz1Id5vZ5p7e0S0F+AEd55sz9JyGokPaBbDJHFVdW+A
IAHg6Xpxmglu3BtbDtBmCA==

/
select
  percent_decimal,
  "."(percent_decimal) as percent_modified
from condition;

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

必須使用內置函式嗎?沒問題。

select
 percent_decimal,
 round(percent_decimal/1.05, 1) as percent_modified
from condition;

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

引用自:https://dba.stackexchange.com/questions/197823