SQL - 计数 WHERE AGGREGATE>1
想象一下,我有一个包含 {id,username,firstname,lastname} 的客户数据库表,
如果我想查找有多少个不同名字的实例,我可以这样做:
select firstname, count(*) from Customers group by 2 order by 1;
firstname | count(*)
====================
bob | 1
jeff | 2
adam | 5
如何计算多次出现的名字的数量?在伪 sql 中,它会是这样的:
select
COUNT(
firstname,
count(*) as num_occurrences
)
from
Customers
group by 2
having num_occurrences > 1;
Imagine I have a db table of Customers containing {id,username,firstname,lastname}
If I want to find how many instances there are of different firstnames I can do:
select firstname, count(*) from Customers group by 2 order by 1;
firstname | count(*)
====================
bob | 1
jeff | 2
adam | 5
How do I count the number of firstnames that occur more than once? In pseudo-sql it would be something like:
select
COUNT(
firstname,
count(*) as num_occurrences
)
from
Customers
group by 2
having num_occurrences > 1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的想法是正确的:
子查询对出现多次的名字进行计数。然后你数一下所有这些名字。
HAVING
子句允许您按聚合进行过滤。它类似于WHERE
子句,只不过您可以使用聚合函数。You have the right idea:
The subquery counts the first names that have occurred more than once. Then you count all of those first names. The
HAVING
clause allows you to filter by aggregates. It's like aWHERE
clause, except you can use aggregate functions.不需要子查询。
尝试:
或者,按最常见的名称排序:
There is no need for a subquery.
Try:
Or, order by the most represented name:
这样就可以做到:
This would do it: