Situation: I have the exchange rate table like this:
date_from cur1 coef1 cur2 coef2
2017-01-01 CZK 27.000000000 EUR 1.000000000
2017-07-03 EUR 1.000000000 CZK 26.150000000
2017-07-03 JPY 100.000000000 CZK 19.500000000
2017-10-05 JPY 1000.0000000 EUR 7.54761885
Notice that sometimes the cur1
and cur2
can be switched for the same pair. The table contains also other currency pairs. The reason for the two coefficients is that the table is filled manually (to get the numbers more comprehensible by a human brain -- see the JPY conversion).
Then I have another table with invoice rows where the price is expressed in the local currency (that is, each row has it own currency unit near the price value).
I need to do some SELECT
over the invoice-row table and transform the price to be shown in the chosen target currency (say, everything in Euro). How to do that efficiently?
My first attempts: I know the target currency in advance. It means it should probably be better to build a temporary table with simplified structure to be joined easily. Let the target currency be EUR. Then only subset of the above table will be used, some pairs be switched, and the two coefficients be converted to one rate. The target currency will be fixed or implicit. From the above table, the JPY-CZK pair would not be part of the table:
date_from cur rate
2017-01-01 CZK 27.000000000
2017-07-03 CZK 26.150000000
2017-10-05 JPY 0.00754761885
To join the rows with another table I need not only the date_from
but also date_to
. To be able to use BETWEEN
in the join condition, I would like to have the date_to
as the one just before the next period. Here for CZK, I need to have a record like:
date_from date_to cur rate
2017-01-01 2017-07-02 CZK 27.000000000
Notice the one day off in the date_to
from the next date_from
.
However, I need to add automatically also some boundary values for the dates before and after the explicitly expressed intervals. I need something like that:
date_from date_to cur rate
1900-01-01 2016-12-31 CZK 27.000000000 <-- guessed rate from the next; fixed start at the year 1900
2017-01-01 2017-07-02 CZK 27.000000000
2017-07-03 3000-01-01 CZK 26.150000000 <-- explicit rate; boundary year to 3000
Plus similarly for the other currencies in the same temporary table...
1900-01-01 2017-10-04 JPY 0.00754761885 <-- rate guessed from the next; fictional date_from
2017-10-05 3000-01-01 JPY 0.00754761885 <-- explicit rate; fictional date_to
How can I efficiently construct such temporary table?
Do you have any other suggestions related to the problem?
Update: I have posted my solution to Code Review https://codereview.stackexchange.com/q/177517/16189 Please, have a look to find the flaws.