[英]SQL - calculate average exchange rate for given periods and use in select
第一次海报在这里。
我有两个表1)交易( T1 )2)汇率( T2 )。 T1持有几种货币的每日交易,T2持有所有货币的每日汇率。
首先,我想计算给定期间每种货币的平均汇率(例如,2016年1月1日至2016年6月30日之间的美元汇率)。
然后,我想通过计算出的平均汇率得出交易和转换后的货币金额,以便美元交易使用计算出的美元AV。 汇率,给我英镑平均汇率,欧元给我欧元汇率。 每行的转化率等。
得出平均率的SQL如下所示;
select currency,avg(b.exch_rate) as avg_rate
from uviexchrates b
where date_from >'2015-01-01' and date_from < '2015-12-31'
and b.rates_to='gbp' and b.client like 'gc' group by b.currency
以上给我的东西是;
currency avg_rate
AUD 2.04
CAD 1.96
CHF 1.47
USD 1.41
我对交易表的查询是;
select currency,cur_amount from agltransact
where period between '201600' and '201606'
我追求的结果是;
cur_amount currency Av_rate converted_amount
-357000.00 EUR 1.12 -318153.46
6.55 EUR 1.12 5.84
6.55 EUR 1.12 5.84
27.77 USD 1.41 19.68
7.86 AUD 2.04 3.86
27.09 USD 1.41 19.20
54.98 CAD 1.96 28.11
计算最右边的2列。 来自第一个查询的av_rate和converted_amount是cur_amount * av_rate的结果。
题; 我如何结合这两个查询,以便产生以上结果?
希望是清楚的。
非常感谢
SELECT T1.cur_amount ,
T1.currency ,
T2.avg_rate ,
T1.cur_amount * T2.avg_rate AS converted_amount
FROM ( SELECT currency ,
cur_amount
FROM agltransact
WHERE period BETWEEN '201600' AND '201606'
) T1
LEFT OUTER JOIN ( SELECT currency ,
AVG(b.exch_rate) AS avg_rate
FROM uviexchrates b
WHERE date_from > '2015-01-01'
AND date_from < '2015-12-31'
AND b.rates_to = 'gbp'
AND b.client LIKE 'gc'
GROUP BY b.currency
) T2 ON T1.currency = T2.currency
我将使用left join
连接将第二个表连接到第一个查询:
select t.currency, t.cur_amount, e.avg_rate, t_cur_amount / e.avg_rate
from agltransact t left join
(select e.currency, avg(b.exch_rate) as avg_rate
from uviexchrates e
where e.date_from >= '2016-01-01' and e.date_from <= '2016-06-30' and
e.rates_to = 'gbp' and
e.client like 'gc'
group by e.currency
) e
on t.currency = e.currency
where t.period between '201600' and '201606' ;
注意:我更改了第一个查询中的日期以匹配文本中的描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.