或者至少我认为它们被称为子查询(新手和SQLite中的自我训练)。我在同一个数据库中的两个表中有两个SELECT
语句。我想在列date
和symbol
上加入这两个子查询。子查询可以单独运行,但是当我尝试JOIN
时出现错误(error in statement: near "JOIN": syntax error
)。这是我的查询字符串:
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))
谢谢!
答案 0 :(得分:13)
您的JOIN子句需要在GROUP BY子句之前。此外,我知道sqlite确实有一些不同的“可选”连接语法,但以下更标准的查询应该有效:
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
如果您对oi和contract_settle列有更多了解(例如,它们永远不会都是负数),a.oi <> 0 AND a.contract_settle <> 0
的WHERE子句可能会有更好的性能。
答案 1 :(得分:1)
您需要通过on子句定义联接方式。我不知道SQLite,但在SQL中,它会像这样(可能不会运行):
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