17. Convert at the rate of the day Solved
AdvancedExpertASOF JOINpoint-in-time lookupscurrencies
Delivered orders were charged in EUR, but non-EUR customers want their totals in their own currency. Convert each delivered, non-EUR order's total at the fx_rates rate for its currency that was valid when the order was placed (the latest valid_from at or before placed_at; per_eur is units of that currency per EUR). Return per currency: currency, orders, total_eur and total_local (sum of converted totals, rounded to 2 decimals). Sort by currency.
Your answer returns 3 rows with the columns currency, orders, total_eur, total_local. Order matters.
The data
The store from the DuckDB playground, running in your browser with DuckDB. Prices are in EUR; the data covers 2024.
customers20 rows
id | INTEGER primary key |
name | VARCHAR |
country | VARCHAR |
currency | VARCHAR EUR, GBP, USD or JPY |
signed_up | DATE |
tags | VARCHAR[] a list: vip, newsletter, b2b, returns-often |
products10 rows
id | INTEGER primary key |
name | VARCHAR |
category | VARCHAR |
price | DECIMAL(10,2) EUR |
specs | STRUCT weight_g INTEGER, color VARCHAR, sizes VARCHAR[] |
orders300 rows
id | INTEGER primary key |
customer_id | INTEGER → customers.id |
placed_at | TIMESTAMP 2024 |
status | ENUM placed, paid, shipped, delivered, returned |
currency | VARCHAR the customer's currency |
order_items576 rows
order_id | INTEGER → orders.id |
product_id | INTEGER → products.id |
quantity | INTEGER |
unit_price | DECIMAL(10,2) EUR |
web_events20,000 rows
event_id | BIGINT |
ts | TIMESTAMP |
session_id | VARCHAR |
customer_id | INTEGER NULL for anonymous visitors |
event_type | VARCHAR page_view, search, add_to_cart, checkout |
page | STRUCT path, referrer |
device | STRUCT browser, mobile BOOLEAN, screen STRUCT(w, h) |
product_ids | INTEGER[] |
load_ms | INTEGER |
fx_rates720 rows
currency | VARCHAR USD, GBP, JPY |
valid_from | TIMESTAMP |
per_eur | DOUBLE units of currency per 1 EUR |
Hints
ASOF JOIN ... ON currency matches AND valid_from <= placed_at picks the latest earlier rate.Common traps
- Joining on the date alone picks the wrong rate when it changed during the day.
- Rounding each order before summing gives a slightly different total.
Solution
WITH totals AS (
SELECT o.id, o.currency, o.placed_at, sum(oi.quantity * oi.unit_price) AS total_eur
FROM orders o JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered' AND o.currency <> 'EUR'
GROUP BY o.id, o.currency, o.placed_at
)
SELECT t.currency, count(*) AS orders, sum(t.total_eur) AS total_eur,
round(sum(t.total_eur * fx.per_eur), 2) AS total_local
FROM totals t
ASOF JOIN fx_rates fx ON fx.currency = t.currency AND fx.valid_from <= t.placed_at
GROUP BY t.currency
ORDER BY t.currency
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.