Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite -- joining two subqueries

Or at least I think they're called subqueries (newbie and self-trained in SQLite). I have two SELECT statements from two tables in the same database. I would like to join these two subqueries along the columns date and symbol. The subqueries work fine separately, but when I try to JOIN I get an error (error in statement: near "JOIN": syntax error). Here's my query string:

SELECT date, symbol, SUM(oi*contract_settle) AS oi_dollar
    FROM (SELECT date, symbol, oi, contract_settle
            FROM ann
            UNION
            SELECT date, symbol, oi, contract_settle
            FROM qtr) 
    GROUP BY date, symbol
    HAVING oi_dollar > 0
    JOIN
    (SELECT date, symbol, ret FROM crsp
    USING (date, symbol))

Thanks!

like image 587
Richard Herron Avatar asked Nov 05 '10 22:11

Richard Herron


2 Answers

Your JOIN clause needs to be before the GROUP BY clause. Also, I know sqlite does has a few different "optional" syntaxes for joins, but the following more standard query should work:

SELECT a.date, a.symbol, SUM(a.oi * a.contract_settle) AS oi_dollar
FROM (SELECT date, symbol, oi, contract_settle
        FROM ann
        UNION
        SELECT date, symbol, oi, contract_settle
        FROM qtr) a
INNER JOIN crsp c ON a.date = c.date AND a.symbol = c.symbol
WHERE a.oi * a.contract_settle > 0
GROUP BY a.date, a.symbol

If you know slightly more about the oi and contract_settle columns (like, that they can never both be negative), a WHERE clause of a.oi <> 0 AND a.contract_settle <> 0 might have better performance.

like image 62
Andrew Avatar answered Oct 13 '22 11:10

Andrew


You need to define how you are joining by an on clause. I don't know about SQLite, but in SQL, it would be like this (may not run):

SELECT date, symbol, SUM(oi*contract_settle) AS oi_dollar
    FROM (SELECT date, symbol, oi, contract_settle
            FROM ann
            UNION
            SELECT date, symbol, oi, contract_settle
            FROM qtr) as 'a'
    JOIN
    (SELECT date, symbol, ret FROM crsp
    USING (date, symbol)) as 'b'
    ON a.date = b.date AND a.symbol = b.symbol
    GROUP BY date, symbol
    HAVING oi_dollar > 0
like image 45
Bryan Denny Avatar answered Oct 13 '22 10:10

Bryan Denny