我在oracle,表1和表2中有2个表
表1
mm/yy order-id cost currency
------- --------- ------ --------
01/17 1 25 pound
03/17 2 30 euro
04/17 3 16 pound
05/17 4 14 pound
06/17 5 10 euro
06/17 6 10 usd
表2
dd/mm/yy currency Conversion_rate_to_USD
------------ ---------- --------------------
01/01/17 pound 1.24
02/01/17 pound 1.23
03/01/17 pound 1.26
........ ...... ....
........ ...... ....
........ ...... ....
01/04/17 pound 1.24
02/04/17 pound 1.23
03/05/17 pound 1.26
........ ...... ....
........ ...... ....
........ ...... ....
01/03/17 euro 1.15
02/03/17 euro 1.16
03/06/17 euro 1.11
01/06/17 euro 1.07
我想检索表1中每行的以美元换算的成本(使用表2中的月份平均转换成本)。
先谢谢
答案 0 :(得分:1)
这个答案假定" date"列确实存储为日期。日期函数在不同数据库中有所不同,但这个(或略有变体)应该适用于大多数数据库。
从表2获得每月平均值:
select year(ddmmyy), month(ddmmyy), currency, avg(Conversion_rate_to_USD)
from table2
group by year(ddmmyy), month(ddmmyy), currency;
要进行转换,请将其用作子查询:
select t1.*,
(t1.cost * t2.avg_c) as cost_in_usd
from table1 t1 join
(select year(ddmmyy) as yr, month(ddmmyy) as mon, currency,
avg(Conversion_rate_to_USD) as avg_c
from table2
group by year(ddmmyy), month(ddmmyy), currency
) t2
on t2.yr = year(t1.mmyy) and t2.mon = year(t1.mmyy) and
t2.currency = t1.currency;