我在两张表下面有样本数据。表A包含每年的美元汇率(印度卢比),表B包含每年的金额。我想转换 美元兑换卢比每年。
Table A
Rate Year
47 2001
49 2003
55 2004
Table B
Amt Year
25$ 2001
34$ 2002
问题:对于第一个记录(2001年),我们在两个表中都有条目,因此我们可以使用以下查询轻松完成此操作
sel A.Rate * B.Amt
from A,
B
where B.year = A.year
但是对于第二个记录(即2002年),我们没有表A中的条目(这是费率表),所以对于这些类型的情况,我想使用上一年的利率值(即:2001年的47卢比。 )
答案 0 :(得分:1)
以下是解决方案:
select A.rate*B.amt
from A,B
where B.Year = (select max(year) from B where B.year <= A.year);
答案 1 :(得分:0)
Oracle:使用LEAD分析功能,这样您就可以计算每个费率的有效期。
这是我的代码:
SELECT
trx.*
,rates.rate_start_date
,rates.rate_end_date
,rates.rate
,trx.amount * rates.rate rup_amount
FROM
xxcjp_forex_trx trx
--this inline view works out the validity period of each rate by ordering all
--the rates and working out the start date of the next row. It uses analytic
--function LEAD
,(SELECT
xfr.rate_date rate_start_date
,xfr.rate
,xfr.currency
,(LEAD(xfr.rate_date) OVER (ORDER BY xfr.currency, xfr.rate_date))-1 rate_end_date
FROM
xxcjp_forex_rates xfr
) rates
WHERE 1=1
AND trx.trx_date BETWEEN rates.rate_start_date AND rates.rate_end_date
AND rates.currency = 'RUP'
ORDER BY
trx.trx_date
;
根据这些数据:
CREATE TABLE XXCJP_FOREX_RATES
(rate_date DATE
,currency VARCHAR2(20)
,rate NUMBER
)
;
CREATE TABLE XXCJP_FOREX_TRX
(trx_date DATE
,currency VARCHAR2(20)
,amount NUMBER
)
;
INSERT INTO XXCJP_FOREX_RATES VALUES (TO_DATE('01/03/2016','DD/MM/YYYY'),'RUP',47) ;
INSERT INTO XXCJP_FOREX_RATES VALUES (TO_DATE('03/03/2016','DD/MM/YYYY'),'RUP',49) ;
INSERT INTO XXCJP_FOREX_RATES VALUES (TO_DATE('10/03/2016','DD/MM/YYYY'),'RUP',55) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('01/03/2016','DD/MM/YYYY'),'USD',10) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('02/03/2016','DD/MM/YYYY'),'USD',20) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('03/03/2016','DD/MM/YYYY'),'USD',30) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('04/03/2016','DD/MM/YYYY'),'USD',40) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('05/03/2016','DD/MM/YYYY'),'USD',50) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('06/03/2016','DD/MM/YYYY'),'USD',60) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('07/03/2016','DD/MM/YYYY'),'USD',70) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('08/03/2016','DD/MM/YYYY'),'USD',80) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('09/03/2016','DD/MM/YYYY'),'USD',90) ;
INSERT INTO XXCJP_FOREX_TRX VALUES (TO_DATE('10/03/2016','DD/MM/YYYY'),'USD',100) ;