Suppose a table that contains currency exchange rates, containing the schema:
{ date: "2017-01-03", quote: "2017-01-03", from: "EUR", to: "USD", rate: "A" }
{ date: "2017-01-03", quote: "2017-01-03", from: "GBP", to: "USD", rate: "B" }
{ date: "2017-01-03", quote: "2017-01-03", from: "CHF", to: "USD", rate: "C" }
{ date: "2017-01-04", quote: "2017-01-04", from: "EUR", to: "USD", rate: "D" }
{ date: "2017-01-04", quote: "2017-01-04", from: "GBP", to: "USD", rate: "E" }
{ date: "2017-01-04", quote: "2017-01-05", from: "GBP", to: "USD", rate: "F" }
Question is how to write a n1ql query that for any given date will return
all of the latest rates for these currencies.
What I’m trying so far which isn’t working is variants of things like this:
SELECT * from bucket
WHERE from IN ["CHF", "EUR", "GBP"] AND
to = "USD"
ORDER BY date DESC, quote DESC LIMIT 3;
(But this doesn’t work because it fails to de-duplicate pairs)
This is not simple because:
- On a given day, not all pairs may be present. On Jan 4, CHF->USD is missing,
and should be taken from Jan 3. - Double timeseries, you can have > 1 observation for a pair on a given day. On
Jan 4, there are two GBP->USD rates, one quoted on the 4th, one quoted on the 5th.
The most up to date one (quote: “2017-01-05”) should be taken - Must have 1 and only 1 reference for each from->to pair on any given day.
Ideally, this query, for 2017-01-04 would return (complex case):
{ date: "2017-01-04", quote: "2017-01-04", from: "EUR", to: "USD", rate: "D" }
{ date: "2017-01-04", quote: "2017-01-05", from: "GBP", to: "USD", rate: "F" }
{ date: "2017-01-03", quote: "2017-01-03", from: "CHF", to: "USD", rate: "C" }
and for 2017-01-03 would return (simple case):
{ date: "2017-01-03", quote: "2017-01-03", from: "EUR", to: "USD", rate: "A" }
{ date: "2017-01-03", quote: "2017-01-03", from: "GBP", to: "USD", rate: "B" }
{ date: "2017-01-03", quote: "2017-01-03", from: "CHF", to: "USD", rate: "C" }
I’m thinking that this may require correlated subqueries, but I’m struggling with how to express this. Any suggestions?