SQL只从列中获取金额($符号后面的数字)和百分比(%符号前的数字)

时间:2014-09-03 04:50:48

标签: sql oracle

我有一些规则说明如下,让我们在表1中说明

rule_id   rule_desc
F89   Ded2 + $100 Copay + 20% Coins; $750 Max + $250 Penalty
F70   Ded1+$250Copay+50%;Upto $500 max+50%Penalty

我想从上面两个例子得到的是......

For F89,
Copay = 100
Coins = 20
Max = 750
Penalty = 250

对于F70,

Copay = 250
Coins = 50
Max = 500
Penalty = 0.5 (50/100)

有人可以帮忙写一个SQL查询(我使用的是Oracle SQL Developer),我发现得到的结果是多行或者是Copay,Coins,Max和Penalty的单独列,请尽快帮助我

1 个答案:

答案 0 :(得分:1)

您的要求似乎随着每个描述而变化。对于您提供的数据类型以及某些假设,此查询可能会有所帮助 -

WITH tab(rule_id, rule_desc) AS 
  (SELECT 'F89', 'Ded2 + $100 Copay + 20% Coins; $750 Max + $250 Penalty' from dual union all
   SELECT 'F70', 'Ded1+$250Copay+50%;Upto $500 max+50%Penalty' FROM dual union all
   SELECT 'F71', '$50 Copay' FROM dual union all
   SELECT 'F72', 'Ded1 + 20% Coins' FROM dual),
-----------------------------------------------
---- End of data preparation
-----------------------------------------------
temp_table as (SELECT rule_id, REGEXP_SUBSTR (rule_desc,'[^\+|;]+',1,LEVEL) txt
                 FROM tab
              CONNECT BY REGEXP_SUBSTR (rule_desc,'[^\+|;]+',1,LEVEL) IS NOT NULL
                  AND PRIOR rule_desc = rule_desc
                  AND PRIOR sys_guid() IS NOT NULL),
final_table as (
SELECT RULE_ID, TXT,
       coalesce(REGEXP_SUBSTR(replace(TXT, 'Upto'), '[a-z,A-Z]+'), 'Coins') "KEY",
       REGEXP_SUBSTR(TXT, '[0-9]+') "VALUE",
       REGEXP_SUBSTR(TXT, '\W+') "SIGN"
  FROM temp_table)
SELECT RULE_ID,
       KEY ||'='||
       case when SIGN = '%' and KEY = 'Penalty' then
           to_char(VALUE / 100)
       else
           VALUE
       end STR
  FROM final_table
 WHERE key not in ('Ded');

输出:

| RULE_ID |         STR |
|---------|-------------|
|     F71 |    Copay=50 |
|     F72 |    Coins=20 |
|     F70 |   Copay=250 |
|     F70 |    Coins=50 |
|     F70 |     max=500 |
|     F70 |  Penalty=.5 |
|     F89 |   Copay=100 |
|     F89 |    Coins=20 |
|     F89 |     Max=750 |
|     F89 | Penalty=250 |

Assumtions:

1)只有缺失的密钥可以是“硬币”

2)百分比计算仅适用于惩罚。

3)惩罚KEY只能包含我们必须替换的“Upto”字符串。在此查询中,将从所有键中删除“Upto”。

我不确定它可能会对你有所帮助,但我希望它能为你带来一些帮助。