SQL - WHERE AGGREGATE> 1

时间:2009-07-31 14:56:47

标签: sql aggregate informix

想象一下,我有一个包含{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的行。

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:4)

我应该说,{p> group by 2 order by 1很可怕。如果支持,请使用正确的列名:这将大大提高可读性。

考虑到这一点,

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

答案 2 :(得分:2)

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

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