我有一个像这样的选择结果:
ID | Amount
---------------
xx1 | 105
xx2 | 70
如果金额大于50,我想将行拆分为多行,结果是:
ID | Amount
---------------
xx1 | 50
xx1 | 50
xx1 | 5
xx2 | 50
xx2 | 20
答案 0 :(得分:3)
递归解决方案:
WITH t(id, amount) AS
(SELECT id, amount
FROM mytable
UNION ALL
SELECT id, amount - 50
FROM t
WHERE amount - 50 > 0)
SELECT id
,least(amount, 50) amount
FROM t
ORDER BY id
,least(amount, 50) DESC
遵循Frank Schmitt的评论。一个MODEL
解决方案应该在Oracle 10g中运行:
SELECT id
, least(amt, 50) amount
FROM
(SELECT id
, amt
FROM mytable t
MODEL
PARTITION BY (id)
DIMENSION BY (0 d)
MEASURES (amount amt)
RULES ITERATE (1024) UNTIL (amt[ITERATION_NUMBER] < 50)
( amt[ITERATION_NUMBER+1] = amt[ITERATION_NUMBER] - 50 ))
WHERE amt > 0
ORDER BY id
, amt DESC
您应确保1024 * 50&gt; = max(金额),或更改要执行的最大迭代次数。