SQL - 计算WHERE AGGREGATE> 1

时间:2009-09-02 17:05:06

标签: sql aggregate informix

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

3 个答案:

答案 0 :(得分:5)

你有正确的想法:

SELECT COUNT(*)
FROM (
  SELECT firstname
  FROM Customers
  GROUP BY firstname
  HAVING COUNT(*) >= 2
)

子查询计算多次出现的名字。然后你算上所有这些名字。 HAVING子句允许您按聚合进行过滤。它就像一个WHERE子句,除了你可以使用聚合函数。

答案 1 :(得分:2)

不需要子查询。

尝试:

SELECT firstname, COUNT(*)
  FROM Customers
 GROUP BY firstname
HAVING COUNT(*) > 1
 ORDER BY firstname

或者,按照最具代表性的名称排序:

SELECT firstname, COUNT(*) AS custcount
  FROM Customers
 GROUP BY firstname
HAVING COUNT(*) > 1
 ORDER BY custcount DESC;

答案 2 :(得分:1)

这样就可以了:

select count(username)
  from (select username
          from Customers
         group by username
        having count(*) > 1);