【发布时间】:2012-07-12 08:13:53
【问题描述】:
我需要将 1 个金额分成 2 个字段。我知道结果字段的总和 = 分割第一行的比率,但我需要将结果总和舍入,然后才计算下一行的比率(所以四舍五入的总和值将是正确的)。
如何在 Oracle 10g PL/SQL 中编写此算法?我需要测试一些迁移的数据。这是我想出的(到目前为止):
with temp as (
select 1 id, 200 amount, 642 total_a from dual union all
select 2, 200, 642 from dual union all
select 3, 200, 642 from dual union all
select 4, 200, 642 from dual union all
select 5, 200, 642 from dual
)
select
temp2.*,
remaining_a / remaining_amount ratio,
round(amount * remaining_a / remaining_amount, 0) rounded_a,
round(amount - amount * remaining_a / remaining_amount, 0) rounded_b
from (
select
temp.id,
temp.amount,
sum(amount) over (
order by id
range between current row and unbounded following
) remaining_amount,
case when id=1 then total_a /* else ??? */ end remaining_a
from temp
) temp2
更新:如果您看不到上面的图片,预计 rounded_A 值为:
1 128
2 129
3 128
4 129
5 128
【问题讨论】:
-
分配... 仅使用 SQL 并不容易。在 CURSOR 循环而不是 SQL 语句中可能值得这样做。
-
@NWest 任何 PL/SQL,我只是在 PL 部分没有足够的经验来自己弄清楚;) 哦 - 简单选择 1 份合同需要一些秒,我需要解决所有 100 000 条记录的解决方案,以便在几个小时内完成,而不是几天......
-
给定
TEMP中的示例输入,您想要的输出是什么? -
您可以这样做,至少对于您提供的数据而言。在不知道如何在 Oracle 中使用查询进行查询之前,您的真实数据是否与此相同,每天的数量相同,所有日期的比例相同?
-
@JustinCave 图片中的 Rounded_A 和 Rounded_B 列