Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to have a left join involving a sub query?
    primarykey
    data
    text
    <p>Please help with a problem I'm facing to properly join a few tables <strong>in a single query</strong>.</p> <p>Simplified schema is as follows:</p> <pre><code>TRANSACTION TABLE: ----------------- TRANSACTION_DATE AMOUNT CURRENCY ---------------- ---------- -------- 22/09/13 100 EUR 22/09/13 200 FRA 22/09/13 200 GBP CURRENCY_CONVERSION TABLE: ------------------------- FROM_CURRENCY TO_CURRENCY CONVERSION_DATE CONVERSION_RATE ------------- ----------- --------------- --------------- GBP USD 23/09/13 1.61 EUR USD 22/09/13 1.35 </code></pre> <p>Presently, the query that works is as follows (using Sybase/SQL Server join syntax)</p> <pre><code>SELECT t.transaction_date, t.amount, t.currency, t.amount * cc.conversion_rate as amount_usd FROM transaction t, currency_conversion cc, WHERE t.transaction_date *= cc.conversion_date AND t.currency *= cc.from_currency AND cc.to_currency = 'USD' </code></pre> <p>We face issue in above query when currency_conversion table may not have conversion rate for certain dates. In this case of missing value, business wants to resort to last latest conversion rate available in DB. For example, if EUR to USD rate is not available for today, use yesterday's rate. I try to do this as follows:</p> <pre><code>SELECT t.transaction_date, t.amount, t.currency, t.amount * cc.conversion_rate as amount_usd FROM transaction t, currency_conversion cc, WHERE t.transaction_date *= (SELECT max(c1.conversion_date) FROM currency_conversion c1 WHERE c1.from_currency = t.from_currency AND c1.to_currency = 'USD') AND t.currency *= cc.from_currency AND cc.to_currency = 'USD' </code></pre> <p>This query does not works. The left join on t.transaction_date is illegal. It would work if I let go of the join but then I miss some transactions in the final result.</p> <p>Please advise.</p> <p>Please note that:</p> <ul> <li>its important to achive this in a single query (two step solution with two queries won't help) <ul> <li>DB used is Sybase 12 though I think this is a generic SQL stuff</li> <li>this is a simplified schema, in the actual query I use there are two more such conversions to USD required for different amounts</li> <li>if possible, please suggest a solution around the existing query with minimal changes</li> </ul></li> </ul> <p>Thanks for your time.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload