The situation
Finance reports all transactions in INR. Exchange rates are published at irregular times, sometimes several times a day, and each rate applies from the moment it is published until the next one for that currency.
Every transaction must be converted with the rate that was in force when it happened, not today's rate and not a daily average.
Input tables
transactions
One row per transaction.
| Column | Type | Description |
|---|---|---|
txn_id |
BIGINT | Unique. |
currency |
STRING | Currency code of the transaction, for example USD or INR. |
amount |
DECIMAL(12,2) | Amount in that currency. |
txn_time |
TIMESTAMP_NTZ | When the transaction happened. |
exchange_rates
One row per published rate. Some rows were delivered twice and are identical in
every column. exchange_rates has no rows for INR.
| Column | Type | Description |
|---|---|---|
currency |
STRING | The foreign currency. |
rate_to_inr |
DECIMAL(10,4) | INR for one unit of the currency. |
valid_from |
TIMESTAMP_NTZ | The rate applies from this moment until the currency's next rate. |
Requirement
Return every transaction exactly once, with the rate used and the amount in INR.
- Use the rate of the transaction's currency with the latest
valid_fromthat is at or beforetxn_time. A rate published at the exact moment of the transaction applies to it. - INR transactions use a rate of 1.
- If no rate for the currency had been published by
txn_time, the transaction still appears, withrate_to_inrandamount_inrboth NULL. amount_inrisamounttimes the rate, rounded to 2 decimals (half up, which is what Spark'srounddoes).
Expected output
One row per transaction.
| Column | Type | Description |
|---|---|---|
txn_id |
BIGINT | |
currency |
STRING | |
amount |
DECIMAL(12,2) | The original amount. |
rate_to_inr |
DECIMAL(10,4) | The rate used. 1.0000 for INR. NULL if no rate was known. |
amount_inr |
DECIMAL(16,2) | NULL if no rate was known. |
Explanation
Show explanationGives the answer away. Try the problem first.
The approach
This is an as-of join, also called a point-in-time join: for each row on the left, find the latest row on the right that is not in the future. Spark has no built-in as-of join for DataFrames, so it is built from a range join and a window.
1. Join each transaction to every rate that was already valid.
already_valid = (F.col("rate_currency") == F.col("currency")) & (F.col("valid_from") <= F.col("txn_time"))
matched = txns.join(rates, already_valid, "left")
A transaction now has one row per earlier rate of its currency. On this data that is 1,387 rows for 160 transactions. It has to be a left join: a transaction with no earlier rate must survive, with NULLs on the rate side.
2. Keep the most recent of those rates.
latest_first = Window.partitionBy("txn_id").orderBy(F.col("valid_from").desc())
latest = matched.withColumn("rn", F.row_number().over(latest_first)).filter(F.col("rn") == 1)
row_number returns exactly one row per transaction. That also takes care of rate
rows that were delivered twice: both copies are identical, one of them wins.
3. Handle INR and compute the amount. INR has no rows in exchange_rates, so after
the left join its rate is NULL. Replace it with 1 before multiplying.
On large tables the range join is the expensive part, since Spark cannot use a plain
hash join on an inequality. The usual alternative is to turn each rate into an
interval with lead(valid_from) (valid from, valid until) and join on
valid_from <= txn_time < valid_until, or to union both tables and carry the last
rate forward with last(..., ignorenulls=True) over a window. All three give the same
result; the union-and-window version avoids the range join entirely.
Common wrong answers
Inner join. Returns 129 rows instead of 160. It drops the 13 SGD transactions made before the first SGD rate, the 3 JPY transactions (no rates at all) and all 15 INR transactions. Totals computed from this are short without any error.
Skipping the row_number step. Returns 1,387 rows. Every transaction is repeated
once per earlier rate. Summing amount_inr on this is wrong by an order of magnitude.
Joining on the calendar date. Returns 310 rows. Rates change several times a day, so a transaction matches every rate published that day, including ones published after it. And a transaction on a day with no new rate gets nothing at all.
Using each currency's latest rate. Row count is right, values are wrong. This revalues history every time a new rate is published: last month's report changes when you rerun it.
valid_from < txn_time. Row count is right, values are wrong for the four
transactions made at the exact moment a rate was published. They get the previous
rate. The rule says "at or before".
Sorting ascending. Picks the earliest rate that was valid, which is the first rate ever published for the currency.
Forgetting INR. Row count is right; the 15 INR transactions have a NULL rate and amount instead of 1.0000 and the original amount.
Edge cases in the data
| Case | Where | What it catches |
|---|---|---|
| Transactions before the currency's first rate | 13 SGD transactions | Inner join; filling in a later rate. |
| Currency with no rates at all | 3 JPY transactions | Inner join. |
| Base currency not in the rates table | 15 INR transactions | Missing the rate of 1. |
Transaction at the exact valid_from of a rate |
4 transactions | < instead of <=. |
| Several rates per currency per day | all currencies | Joining on the date. |
| Rate rows delivered twice | 3 rows | Duplicated output rows in interval-based solutions. |