我知道如果我們在 select 陳述句中直接使用它會起作用
從雙中選擇 (6*5 2/4);
這將產生輸出 30.5 但我的期望是
6*5 = 30 2 = 32 / 4 = 8 它應該回傳 8
有沒有辦法做這樣的計算?
uj5u.com熱心網友回復:
下面的解決方案假設所有輸入都是非負整數,輸入運算式中沒有括號和空格,并且沒有被零除。
如果輸入有括號,則可以先將其洗掉。如果有空格,它們也可以先洗掉。如果輸入可能包括小數和/或負數,也可以容納,但需要做更多的作業。
策略:先插入括號強制求值順序;這顯示在new_str中間結果中(在prep子查詢中)。我們還需要將“/”更改為“div”以在 XQuery 中使用。
然后只需使用 XQuery 來評估生成的算術運算式字串。
with
test_data (str) as (
select '6*5 2/4' from dual union all
select '332' from dual union all
select '12 3*5/75' from dual
)
, prep (str, new_str) as (
select str,
replace(
rpad('(', length(regexp_replace(str, '\d')), '(') ||
regexp_replace(str, '([- */])', ')\1')
, '/', ' div ')
from test_data
)
select str, new_str,
xmlcast(xmlquery(new_str returning content) as number) as result
from prep;
STR NEW_STR RESULT
--------- ------------------- -------
6*5 2/4 (((6)*5) 2) div 4 8
332 332 332
12 3*5/75 (((12) 3)*5) div 75 1
uj5u.com熱心網友回復:
您可以使用遞回查詢:
WITH perform_calculation (value, calculation) AS (
SELECT value,
value
FROM table_name
UNION ALL
SELECT value,
CASE REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 2)
WHEN ' ' THEN REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1)
REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 3)
WHEN '-' THEN REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1)
-
REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 3)
WHEN '*' THEN REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1)
*
REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 3)
WHEN '/' THEN REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1)
/
REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 3)
END
|| REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 4)
FROM perform_calculation
WHERE REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1) IS NOT NULL
)
SEARCH DEPTH FIRST BY value SET value_order
SELECT value,
calculation
FROM perform_calculation
WHERE REGEXP_SUBSTR(calculation, '^(-?\d \.?\d*)([ */-])(-?\d \.?\d*)(.*)$', 1, 1, NULL, 1) IS NULL;
其中,對于樣本資料:
CREATE TABLE table_name (value) AS
SELECT '6*5 2/4' FROM DUAL UNION ALL
SELECT '6*5 2/4' FROM DUAL UNION ALL
SELECT '32/4*3/2 24/4 3/6' FROM DUAL UNION ALL
SELECT '3/2-3*5' FROM DUAL;
輸出:
價值 計算 3/2-3*5 -7.5 32/4*3/2 24/4 3/6 2 6*5 2/4 8 6*5 2/4 8
db<>在這里擺弄
uj5u.com熱心網友回復:
除法優先于加法,因此您的計算默認為:
(6*5) (2/4)
如果要更改默認優先級,則需要使用括號:
(6*5 2)/4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/398210.html
