SQL - WHERE AGGREGATE>1

发布于 2024-07-30 00:38:53 字数 349 浏览 5 评论 0原文

想象一下,我有一个包含 {id,username,firstname,lastname} 的客户数据库表,

如果我想查找有多少个不同名字的实例,我可以这样做:

select firstname,count(*) from Customers group by 2 order by 1;

   username | count(*)
   ===================
   bob      |   1
   jeff     |   2
   adam     |   5

如何编写相同的查询以仅返回出现次数超过的名字一次? 即在上面的示例中仅返回 jeff 和 adam 的行。

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;

   username | count(*)
   ===================
   bob      |   1
   jeff     |   2
   adam     |   5

How do I write the same query to only return firstnames that occur more than once? i.e. in the above example only return the rows for jeff and adam.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

無處可尋 2024-08-06 00:38:54

您需要 having 子句,如下所示:

select 
    firstname,
    count(*) 
from Customers 
group by firstname
having count(*) > 1
order by 1

You want the having clause, like so:

select 
    firstname,
    count(*) 
from Customers 
group by firstname
having count(*) > 1
order by 1
标点 2024-08-06 00:38:54

我应该说,group by 2 order by 1 太糟糕了。 如果支持,请使用正确的列名称:这将大大提高可读性。

考虑到这一点,

select firstname, count(*) c 
from Customers 
group by firstname  
having count(*) > 1 -- Kudos to Shannon
order by c;

group by 2 order by 1 is terrible, I should say. Use proper column names if that's supported: this will drastically improve readability.

With that in mind,

select firstname, count(*) c 
from Customers 
group by firstname  
having count(*) > 1 -- Kudos to Shannon
order by c;
記柔刀 2024-08-06 00:38:54

这就是 HAVING 子句的作用。 我不确定这是否适用于 informix,但请尝试一下:

select firstname, count(*) 
from Customers 
group by firstname
HAVING COUNT(*) > 1

That's what the HAVING clause does. I'm not sure if this will work in informix, but give it a shot:

select firstname, count(*) 
from Customers 
group by firstname
HAVING COUNT(*) > 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文