这里是第一次发帖。
我有两个表 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 和 conversion_amount 是 cur_amount * av_rate 的结果。
问题; 我如何组合这两个查询才能产生上述结果?
希望这是清楚的。
非常感谢
最佳答案
我将使用左连接
将第二个表连接到第一个查询:
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' ;
注意:我更改了第一个查询中的日期以匹配文本中的描述。
关于mysql - SQL - 计算给定时期的平均汇率并在选择中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371649/