|
|
回复 #55 newkid 的帖子
现在有个汇率转化问题,有这样一张表:
create table t_rates(rid number primary key, from_currency varchar2(10),to_currency varchar2(10),conversion_rate number);
--rid 是汇率表的主键,from_currency 是现有金额的币种 ,to_currency是目标币种, conversion_rate是汇率
现有如下数据:
rid from_currency to_currency conversion_rate
1 rmb usd 0.5
2 riyuan usd 0.1
对于我们之前使用的t_money表现在多了一个当前币种字段如下:
alter table t_money add currencyCode varchar2(10);
id amount currencyCode
1 2 rmb
2 2 rmb
3 3 rmb
4 5 rmb
5 2 rmb
6 8 riyuan
7 1 riyuan
8 2 riyuan
9 2 riyuan
10 3 riyuan
还是针对之前讨论的需求,仍然是求组合数据得到总金额,但是现在要先对币种的汇率进行转换,因为现有的金额是人民币和日元,所求的金额的币种是美元,汇率关系分别是:人民币对美元 0.5 日元对美元:0.1,因此在组合计算的时候要先转化为美元,再进行相加。并且当组合金额大于所求金额时,拆分当前最后一笔金额。
我今天写了一条超级繁杂的SQL对应此新需求,执行效率很低,请前辈指点。
--以下是求目标金额为3美元的SQL(含拆分过程)
select main.*,
nvl((select nvl(conversion_rate, 1)
from t_rates
where from_currency = main.org_currency
and upper(to_currency) = 'USD'),
1) rate
from (select id,
total,
amount,
(case
when total <= 3 then
amount
else
(3 - last_total) / nvl((select nvl(conversion_rate, 1)
from t_rates
where from_currency = currencycode
and upper(to_currency) = 'USD'),
1)
end) amount_t,
currencycode org_currency
from (select a.id,
SUM(a.amount_usd) OVER(ORDER BY a.amount_usd, a.id) as total,
SUM(a.amount_usd) OVER(ORDER BY a.amount_usd, a.id) - a.amount_usd as last_total,
a.amount,
a.currencycode
from (select m.amount * nvl(t.conversion_rate, 1) amount_usd,
m.amount,
id,
m.currencycode
from t_rates t, t_money m
where m.currencycode = t.from_currency
and upper(t.to_currency) = 'USD') a)
where total <=
(select min(total)
from (select id, total
from (select a.id,
SUM(a.amount_usd) OVER(ORDER BY a.amount_usd, a.id) as total
from (select m.amount *
nvl(t.conversion_rate, 1) amount_usd,
m.amount,
id
from t_rates t, t_money m
where m.currencycode = t.from_currency
and upper(t.to_currency) = 'USD') a)
where total >= 3))) main |
|