当我执行下面的命令时,它告诉我
#1247 - 参考' StockCount'不支持(参考群组功能)
SELECT stockSymbol, count(*) as StockCount
FROM US500
group by stockSymbol
AND StockCount > 100
ORDER BY stockSymbol DESC
为什么它不起作用。
答案 0 :(得分:2)
SELECT
和任何WHERE
子句在任何聚合GROUP BY
函数之前应用。
如果您尝试这样做,StockCount
子句中的未知列WHERE
会出现错误:
SELECT stockSymbol, count(*) as StockCount
FROM US500
WHERE StockCount > 100
GROUP BY stockSymbol
ORDER BY stockSymbol DESC
相反,请使用在HAVING
,SELECT
和WHERE
之后发生的GROUP BY
来应用条件来汇总来自GROUP BY
的结果:
SELECT stockSymbol, count(*) as StockCount
FROM US500
/* WHERE clause would go here */
GROUP BY stockSymbol
HAVING StockCount > 100
ORDER BY stockSymbol DESC
ORDER BY
最后出现,因此您还可以在那里引用聚合列:
SELECT stockSymbol, count(*) as StockCount
FROM US500
GROUP BY stockSymbol
HAVING StockCount > 100
ORDER BY StockCount DESC
查询中子句的顺序应该可以让您了解它们的处理顺序。例如。 GROUP BY
子句必须位于WHERE
子句之后,HAVING
必须位于GROUP BY
之后。