Monthly USD revenue pivot with as-of FX rate lookups
SQL & DataModel answerLast updated
Convert multi-currency sales to USD with an as-of rate join, pivot revenue by category and region, find August's top customer per region, and flag missing FX rates.
You are building a revenue report for a finance team. Sales are recorded in local currencies, and the report must be in USD using the exchange rate that was in effect on each sale date.
Tables
transactions
| txn_id | txn_date | customer_id | product_id | region | currency | amount |
|---|---|---|---|---|---|---|
| 1 | 2025-08-28 | C1 | P1 | NA | USD | 1200 |
| 2 | 2025-08-30 | C2 | P2 | EU | EUR | 900 |
| 3 | 2025-07-15 | C3 | P1 | APAC | JPY | 150000 |
| 4 | 2025-06-20 | C1 | P3 | NA | USD | 500 |
| 5 | 2025-08-05 | C3 | P2 | EU | EUR | 700 |
| 6 | 2025-07-31 | C2 | P3 | NA | USD | 300 |
fx_rates (rate_to_usd is the number of USD for one unit of the currency)
| currency | rate_date | rate_to_usd |
|---|---|---|
| EUR | 2025-08-29 | 1.10 |
| EUR | 2025-07-31 | 1.12 |
| JPY | 2025-07-10 | 0.0065 |
| JPY | 2025-06-30 | 0.0068 |
products
| product_id | product_name | category |
|---|---|---|
| P1 | Alpha | SaaS |
| P2 | Beta | Services |
| P3 | Gamma | Hardware |
customers
| customer_id | name | segment |
|---|---|---|
| C1 | Acme | Enterprise |
| C2 | Globex | Mid-Market |
| C3 | Initech | SMB |
Tasks
A. USD conversion. For every transaction, find the most recent FX rate dated on or before txn_date, and convert the amount to USD. A rate older than 30 days before the transaction counts as missing. USD rows need no lookup. Return txn_id, txn_date, customer_id, product_id, region, category, segment, amount_usd, fx_missing_flag. Set the flag to 1 when a non-USD transaction has no usable rate, and 0 otherwise. No transaction may be dropped or duplicated.
B. Pivot report. For June through August 2025, return one row per month and product category, with one column per region (NA, EU, APAC) and a Total column, all summing amount_usd. Derive the month from txn_date rather than hardcoding month values.
C. Top customer per region. For August 2025 only, return the one customer with the highest total amount_usd in each region. Break ties first by the highest single-transaction amount_usd in that month, then by customer_id ascending.
D. Data-quality check. List the non-USD transactions that have no FX rate on or before txn_date within the prior 30 days. These must be exactly the rows where fx_missing_flag = 1. In one sentence, explain how you would monitor this in production.
State which SQL dialect you assume, and explain how your queries handle missing rates, empty groups and ties.
Hints
Hint 1
For an as-of lookup, join every rate of the same currency with rate_date <= txn_date (and within 30 days), then use ROW_NUMBER() ordered by rate_date DESC and keep row 1. Put that rn = 1 test in the LEFT JOIN's ON clause, not in WHERE.
Hint 2
A pivot is conditional aggregation: SUM(amount_usd) FILTER (WHERE region = 'EU') or SUM(CASE WHEN ... END) per column, grouped by the month from DATE_TRUNC and the category. Total is the plain SUM.
Hint 3
For the top customer, first aggregate to (region, customer) with SUM and MAX, then rank with ROW_NUMBER() PARTITION BY region ORDER BY total DESC, max_txn DESC, customer_id ASC. Expect no APAC row for August.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
I assume PostgreSQL. All four parts build on one CTE, converted, so the FX logic lives in a single place.
A. As-of join with a 30-day lookback
An equality join on the date would miss most rows, because rates are not published every day. Instead:
- Join each transaction to all rates of the same currency where
rate_date <= txn_date. Rates after the sale date must never be used. - Limit candidates to
rate_date >= txn_date - 30 days. Part D defines a stale rate as missing, so the window belongs in the join condition. - Rank candidates per transaction by
rate_date DESCand keep rank 1. - Use
LEFT JOINfor the rate, product and customer lookups so no transaction is lost or duplicated.
WITH fx_pick AS (
SELECT
t.txn_id,
f.rate_to_usd,
ROW_NUMBER() OVER (
PARTITION BY t.txn_id
ORDER BY f.rate_date DESC
) AS rn
FROM transactions t
JOIN fx_rates f
ON f.currency = t.currency
AND f.rate_date <= t.txn_date
AND f.rate_date >= t.txn_date - INTERVAL '30 days'
),
converted AS (
SELECT
t.txn_id, t.txn_date, t.customer_id, t.product_id, t.region,
p.category,
c.segment,
CASE WHEN t.currency = 'USD' THEN t.amount
ELSE t.amount * fp.rate_to_usd END AS amount_usd,
CASE WHEN t.currency <> 'USD' AND fp.rate_to_usd IS NULL
THEN 1 ELSE 0 END AS fx_missing_flag
FROM transactions t
LEFT JOIN fx_pick fp ON fp.txn_id = t.txn_id AND fp.rn = 1
LEFT JOIN products p ON p.product_id = t.product_id
LEFT JOIN customers c ON c.customer_id = t.customer_id
)
SELECT * FROM converted ORDER BY txn_id;
The condition fp.rn = 1 must be in the ON clause. In WHERE it would filter out every row without a rate and silently turn the left join into an inner join.
Results on the sample data:
| txn_id | rate used | amount_usd | flag |
|---|---|---|---|
| 1 | USD | 1200 | 0 |
| 2 | EUR 08-29 at 1.10 | 990 | 0 |
| 3 | JPY 07-10 at 0.0065 | 975 | 0 |
| 4 | USD | 500 | 0 |
| 5 | EUR 07-31 at 1.12 | 784 | 0 |
| 6 | USD | 300 | 0 |
Two rows show the traps. Transaction 5 must not use the 08-29 EUR rate, because it is dated after the sale. Transaction 3 must use 07-10 rather than the older 06-30 rate.
B. Pivot with conditional aggregation
SELECT
DATE_TRUNC('month', txn_date)::date AS month,
category,
COALESCE(SUM(amount_usd) FILTER (WHERE region = 'NA'), 0) AS "NA",
COALESCE(SUM(amount_usd) FILTER (WHERE region = 'EU'), 0) AS "EU",
COALESCE(SUM(amount_usd) FILTER (WHERE region = 'APAC'), 0) AS "APAC",
COALESCE(SUM(amount_usd), 0) AS "Total",
SUM(fx_missing_flag) AS fx_missing_txns
FROM converted
WHERE txn_date >= DATE '2025-06-01'
AND txn_date < DATE '2025-09-01'
GROUP BY 1, 2
ORDER BY 1, 2;
| month | category | NA | EU | APAC | Total |
|---|---|---|---|---|---|
| 2025-06 | Hardware | 500 | 0 | 0 | 500 |
| 2025-07 | Hardware | 300 | 0 | 0 | 300 |
| 2025-07 | SaaS | 0 | 0 | 975 | 975 |
| 2025-08 | SaaS | 1200 | 0 | 0 | 1200 |
| 2025-08 | Services | 0 | 1774 | 0 | 1774 |
- The month comes from
DATE_TRUNC, so the date range is only a filter. The half-open upper bound is safe even iftxn_dateis a timestamp. Totalis an unfiltered sum, so it also includes any region outside the three listed.SUMignores NULL amounts, so a missing rate would silently under-count. Thefx_missing_txnscolumn exposes that.- Static SQL needs the region list known in advance. For dynamic regions, generate the SQL or pivot in the BI or pandas layer.
C. Top customer per region in August
Aggregate to (region, customer) first, then rank within each region with the full tie-break chain.
, aug AS (
SELECT region, customer_id,
SUM(amount_usd) AS total_usd,
MAX(amount_usd) AS max_txn_usd
FROM converted
WHERE txn_date >= DATE '2025-08-01'
AND txn_date < DATE '2025-09-01'
AND fx_missing_flag = 0
GROUP BY region, customer_id
),
ranked AS (
SELECT aug.*,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY total_usd DESC, max_txn_usd DESC, customer_id ASC
) AS rn
FROM aug
)
SELECT region, customer_id, total_usd, max_txn_usd
FROM ranked
WHERE rn = 1
ORDER BY region;
- NA: C1 with 1200.
- EU: C2 with 990, ahead of C3 with 784.
- APAC: no row, because its only transaction is in July. Empty groups simply do not appear, and it is worth saying so explicitly.
ROW_NUMBER is the right choice here. RANK could return several rows for a region on a tie, whereas ROW_NUMBER with a deterministic ORDER BY always returns exactly one.
D. Missing-rate check
SELECT c.txn_id, c.txn_date, t.currency, t.amount
FROM converted c
JOIN transactions t USING (txn_id)
WHERE c.fx_missing_flag = 1;
On the sample data this returns no rows: transactions 2, 3 and 5 have rates 1, 5 and 5 days old. It would fire for a JPY sale on 2025-08-20 (the latest JPY rate is 41 days old) or for a currency such as GBP that has no rows in fx_rates.
Monitoring: run this query after every FX and transaction load, alert (and optionally block the downstream report) when the flagged count exceeds a set threshold, and also alert when any currency's newest rate_date is more than a day old.
Complexity
The window function sorts the candidate rates per transaction. That costs about O(N log k) for N transactions and k candidate rates each, and an index on fx_rates(currency, rate_date) keeps the join cheap. Parts B to D are single scans of converted plus a small sort or aggregate.
Common mistakes
- Joining on
rate_date = txn_date, which drops almost every row. - Allowing future-dated rates by using the nearest rate instead of the latest one on or before the date.
- Putting
rn = 1inWHERE, which silently removes unmatched rows. - Using inner joins on lookups, which loses transactions with missing metadata.
- Hardcoding months in the pivot, or forgetting that empty cells should show 0.
- Using
RANKfor top-1 and getting duplicate winners, or forgetting the finalcustomer_idtie-break. - Treating a missing rate as 1.0 instead of flagging it, which produces wrong numbers that look plausible.