MySQL计算组中的记录

时间:2014-03-13 17:36:39

标签: mysql

当我执行下面的命令时,它告诉我

  

#1247 - 参考' StockCount'不支持(参考群组功能)

SELECT stockSymbol, count(*) as StockCount 
FROM US500 
group by stockSymbol 
AND StockCount > 100 
ORDER BY stockSymbol DESC 

为什么它不起作用。

1 个答案:

答案 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 

相反,请使用在HAVINGSELECTWHERE之后发生的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之后。