繁体   English   中英

根据COUNT行数过滤分组结果

[英]Filtering grouped results on COUNT of a number of rows

我基本上有一个非常简单的查询,像这样

SELECT accounts . * , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
ORDER BY COUNT(receive) DESC

我尝试将其更改为以下内容,但失败了

SELECT accounts . * , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
    AND total_accounts < 10
GROUP BY followings.receive
ORDER BY COUNT(receive) DESC

Unknown column 'total_counts' in 'where clause'

很抱歉发布这样一个简单的问题,但我的想法现在陷入僵局

首先: 删除表格和*accounts.* 之间的空间

第二:您不能在聚合表达式上使用where 您需要使用having

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
HAVING total_accounts < 10
ORDER BY COUNT(receive) DESC

有关select如何工作的一些指南:

SELECT "Fields and expressions"
FROM "Tables, views and / or subqueries"
WHERE "Conditions to apply on the raw data (contained directly in the FROM clause)"
GROUP BY "Grouping fields"
HAVING "Conditions to apply on the grouped data or (aggregate) expressions"

GROUP BY子句之前过滤,请使用WHERE然后在过滤之前 ,使用HAVING 由于count的汇总是在分组期间发生的,因此它在WHERE子句中给出了错误-在执行时根本不知道。 改成:

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
HAVING count(receive) < 10
ORDER BY COUNT(receive) DESC
SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive  --<-- You need to GROUP BY All the columns
                                 -- In your select that are not containted 
                               -- in any Aggregate Function i.e accounts.*


ORDER BY total_counts DESC  --<-- ORDER BY you need to use the Alias

查询2

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
  --  AND total_accounts < 10 --<-- Where Clause Filters the Rows
                                -- Before doing any aggregates you
                                -- need to use HAVING Clause when checking
                                -- against aggregated values

GROUP BY followings.receive   --<-- You need to GROUP BY All the columns
                                 -- In your select that are not containted 
                               -- in any Aggregate Function i.e accounts.*
HAVING total_accounts < 10
ORDER BY total_counts DESC --<-- ORDER BY you need to use the Alias

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM