我有一张transactions
的表格。这些字段包含id
,trans_date
,amount
,currency
字段。
我有另一张表格fx_rates
,其中包含字段id
,fx_date
,currency
,rate_to_gbp
。
我希望将特定日期的GBP交易金额相加。 E.g。
SELECT format(transactions.trans_date, "mm-yyyy") as monthyear, sum(transactions.amount) as amount_sum
FROM transactions
GROUP BY format(transactions.trans_date, "mm-yyyy");
但是我的一些交易不是英镑。是否可以通过使用子查询对那些transactions.currency <> "GBP"
的字段执行货币转换?
类似的东西:
sum(iif(transactions.currency = "GBP",
transactions.amount,
transactions.amount / (
SELECT fx_rates.rate_to_gbp
WHERE fx_rates.currency = transactions.currency
AND transactions.trans_date = fx_rates.fx_date
))
???
编辑:以下示例数据......
交易:
id account_id trans_date amount currency
----------------------------------------------------
1797 GFSS35 28/01/2005 365000 USD
1798 LA1F8 04/03/2005 100247.57
1799 IDFS12 31/03/2005 2396.89 GBP
1800 DF088 06/04/2005 14000 EUR
1801 BGD005 18/05/2005 450000
汇率:
id fx_date currency rate_to_gbp
-------------------------------------------
3367 25/11/2018 USD 1.62
3368 25/11/2018 EUR 1.2
3369 25/11/2018 CHF 1.47
3412 11/12/2013 USD 1.64
3413 11/12/2013 EUR 1.2
3414 11/12/2013 CHF 1.46
答案 0 :(得分:1)
看起来你应该加入。
SELECT format(transactions.trans_date, "mm-yyyy") as monthyear,
SUM(IIF(transactions.currency = "GBP" OR transactions.currency = "",
transactions.amount,
transactions.amount/fx_rates.rate_to_gbp)) AS amount_sum
FROM transactions
LEFT JOIN fx_rates
ON fx_rates.currency = transactions.currency
AND transactions.trans_date = fx_rates.fx_date
GROUP BY format(transactions.trans_date, "mm-yyyy");
我选择LEFT JOIN因为我不确定当transactions.currency =“GBP”时fx_rates表中是否会有相应的记录。如果应该,我会使用INNER JOIN来避免fx_rates.rate_to_gbp可能为null的任何实例。