想象一下,我有一个包含{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的行。
答案 0 :(得分:10)
您需要having
子句,如下所示:
select
firstname,
count(*)
from Customers
group by firstname
having count(*) > 1
order by 1
答案 1 :(得分:4)
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