我遇到的问题与计算一个字段的值有关,但在前一行使用了值。在带有数据的表RATE
中ID Original Rate Capital
-- ------------------ -------
1 50 1
2 50 + 1 1
3 50 + 1 + 1 1
4 50 + 1 + 1 + 2 2
5 50 + 1 + 1 + 2 + 2 2
公式为:原始汇率(n)=原始汇率(n-1)+资本
在原版中,我有1行,原始费率是50,我希望下一个值应该是原始费率+资本。
我也尝试使用Lag Function,但似乎没有应用于计算字段。
如果你们对这个案子有任何疑问,请帮助我吗?
感谢您的时间!
更新新案例
+----+---------------+------+---------+-------+-------+-------+
| ID | Original Rate | Type | Capital | Rate1 | Rate2 | Rate3 |
+----+---------------+------+---------+-------+-------+-------+
| 1 | 50 | 1 | 2 | 0.1 | | |
| 2 | 50 | 1 | 2 | 0.1 | | |
| 3 | 50 | 1 | 2 | 0.1 | | |
| 4 | 50 | 2 | 1 | | 0.2 | |
| 5 | 50 | 3 | 5 | | | 0.3 |
+----+---------------+------+---------+-------+-------+-------+
New Rate (n) = New Rate (n-1) + Original Rate * IF(Type=1,Rate1*capital,IF(Type=2,Rate2*capital),Rate3*capital)
我期望的输出在最后一栏如下:
+----+---------------+------+---------+-------+-------+-------+-----+
| ID | Original Rate | Type | Capital | Rate1 | Rate2 | Rate3 | |
+----+---------------+------+---------+-------+-------+-------+-----+
| 1 | 50 | 1 | 2 | 0.1 | | | 10 |
| 2 | 50 | 1 | 2 | 0.1 | | | 20 |
| 3 | 50 | 1 | 2 | 0.1 | | | 30 |
| 4 | 50 | 2 | 4 | | 0.2 | | 70 |
| 5 | 50 | 3 | 5 | | | 0.3 | 145 |
+----+---------------+------+---------+-------+-------+-------+-----+
欢迎任何意见和建议!
[2017年4月17日更新] 我使用 Recursion with recursive WITH
实现了提取WITH RATE_MASTER AS (ID, RATE)
(
SELECT 1, ORIGINALRATE FROM RATE WHERE ID = 1
UNION ALL
SELECT ID,
CASE
WHEN TYPE = 1 THEN RATE + Rate1*Capital
WHEN TYPE = 2 THEN RATE + Rate2*Capital
WHEN TYPE = 3 THEN RATE + Rate3*Capital
END AS RATE
FROM RATE, RATE_MASTER
WHERE RATE_MASTER.ID = RATE.ID - 1
)
SELECT * FROM RATE_MASTER;
它运作正常!
[关闭]
答案 0 :(得分:0)
Oracle安装程序:
CREATE TABLE rate ( id, capital ) AS
SELECT 1, 1 FROM DUAL UNION ALL
SELECT 2, 1 FROM DUAL UNION ALL
SELECT 3, 1 FROM DUAL UNION ALL
SELECT 4, 2 FROM DUAL UNION ALL
SELECT 5, 2 FROM DUAL;
<强>查询强>:
SELECT id,
50 + SUM( capital ) OVER ( ORDER BY id )
- FIRST_VALUE( capital ) OVER ( ORDER BY id ) AS rate,
capital
FROM rate;
<强>输出强>:
ID RATE CAPITAL
-- ---- -------
1 50 1
2 51 1
3 52 1
4 54 2
5 56 2