【问题标题】:ORDER BY VS GROUP BY COUNT(*)ORDER BY VS GROUP BY COUNT(*)
【发布时间】:2019-01-27 05:14:48
【问题描述】:

问题: 为什么我无法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。

谢谢

【问题讨论】:

  • ...由于 MySQL 错误:无法在“num_accounts”上分组

标签: group-by count sql-order-by aggregation


【解决方案1】:

处理此 SQL 的顺序与编写它的顺序不同。首先加入,在哪里,组,选择,然后按最后排序。这意味着 num_accounts 在 group by stage 中不存在。你可以改用这个

GROUP BY c.cust_id, COUNT(*)

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    相关资源
    最近更新 更多