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!
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:
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 <> 0might have better performance.