ORDER BY VS GROUP BY COUNT(*)

ORDER BY VS GROUP BY COUNT(*)

问题: 为什么我不能 GROUP BY num_accounts in:

select c.cust_id, COUNT(*) num_accounts
from customer c LEFT JOIN
account a on a.account_id = c.cust_id
GROUP BY c.cust_id, num_accounts;

相反,我必须将“num_accounts”放入 ORDER BY 子句中:

select c.cust_id, COUNT(*) num_accounts
from customer c LEFT JOIN
account a on a.account_id = c.cust_id
GROUP BY c.cust_id
ORDER BY num_accounts;

?

我的假设是 num_accounts 是由聚合生成的列,应该使用 GROUP BY。

感谢

处理此 SQL 的顺序与其写入的顺序不同。首先加入,Where,分组,select,然后按最后排序。这意味着 num_accounts 不存在于 group by stage 中。您可以改用它

GROUP BY c.cust_id, COUNT(*)