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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With