我有一个如下所示的汇率表
FromCurrency ToCurrency ValidFrom ExchangeRate
USD ZAR 2012-01-05 00:00:00.000 7.7260000000
USD ZAR 2012-01-04 00:00:00.000 7.6740000000
USD ZAR 2012-01-03 00:00:00.000 7.4601000000
USD ZAR 2012-01-02 00:00:00.000 7.7600000000
USD ZAR 2012-01-01 00:00:00.000 8.0945000000
EUR NOK 2012-01-05 00:00:00.000 7.5881000000
EUR NOK 2012-01-04 00:00:00.000 7.5974000000
EUR NOK 2012-01-03 00:00:00.000 7.4494000000
EUR NOK 2012-01-02 00:00:00.000 7.6606000000
EUR NOK 2012-01-01 00:00:00.000 7.7740000000
USD AED 2012-01-05 00:00:00.000 3.6731000000
USD AED 2012-01-04 00:00:00.000 3.6731000000
我的主要表是
Transaction Date Amount Currency FromCurrency
13971 5/27/2011 8000 USD USD
13971 7/31/2011 -6809.4 ZAR USD
13971 8/30/2011 -425.59 ZAR USD
13971 9/27/2011 -6809.4 ZAR USD
67467 11/8/2011 5000 GBP GBP
67467 12/21/2011 -5195.06 ZAR GBP
67467 1/30/2012 -5195.06 ZAR GBP
81181 4/15/2011 6000 USD USD
81181 6/28/2011 -5159.03 ZAR USD
82418 10/21/2011 5000 EUR EUR
82418 1/27/2012 -3919.97 NOK EUR
以上是表的示例数据,我的实际表有数百万条记录。我必须将金额乘以汇率栏(来自汇率表),并将相应的FromCurrency(来自汇率表)更新为我表格中的货币栏。
我尝试了很多方法但找不到解决方法。这里棘手的部分是我的表在汇率表中没有匹配的日期。
汇率应该像这样应用。如果我的交易日期是2012年2月20日,货币是ZAR而且FromCurrency是USD,那么我必须从汇率表中选择以下行
USD ZAR 2012-01-02 00:00:00.000 7.7600000000
答案 0 :(得分:1)
update transactions
set FromCurrencyAmount = transactions.amount *
(select top 1 exchangerate from exchangerates where validfrom <= transactions.date
and transactions.fromcurrency = exchangerates.fromcurrency
and transactions.currency = exchangerates.tocurrency
order by validfrom desc)
选择
select transactions.*,
(select top 1 exchangerate from exchangerates where validfrom <= transactions.date
and transactions.fromcurrency = exchangerates.fromcurrency
and transactions.currency = exchangerates.tocurrency
order by validfrom desc)
from transactions
答案 1 :(得分:1)
另一种选择是:
select * from
transact t1 join exchRate e1 on t1.FromCurrency = e1.FromCurrency
and t1.ToCurrency = e1.ToCurrency
and t1.tdate > e1.ValidFrom
and not exists
(select 1 from exchRate where ValidFrom < t1.tdate and ValidFrom > e1.ValidFrom)
答案 2 :(得分:0)
我希望明白
SELECT T3.*,
T4.DATEMAX,
T4.VALUESELECTED
FROM TRANSACTIONS AS T3
INNER JOIN
(SELECT T.CURRENCY,
T.FROMCURRENCY,
T.DATEMAX,
T2.EXCHANGERATE AS VALUESELECTED
FROM (SELECT CURRENCY,
FROMCURRENCY,
MAX(ValidFrom) AS DATEMAX
FROM ExChangeRate
WHERE ValidFrom <= T3.DATE
GROUP BY Currency, FromCurrency) AS T
INNER JOIN
ExChangeRate AS T2
ON T.CURRENCY = T2.CURRENCY
AND T.FROMCURRENCY = T2.FROMCURRENCY
AND T.DATEMAX = T2.VALIDFROM) AS T4
ON T4.CURRENCY = T3.CURRENCY
AND T4.FROMCURRENCY = T3.FROMCURRENCY;