COUNT FUNCTION where子句

时间:2015-03-01 22:27:22

标签: mysql sql oracle

以下查询给出了三个代表每个company_name的列和行。 NR_OF_MEMBER列会告诉我有多少会员加入该公司。

  SELECT COMPANY_NAME, ENROLLMENT_FEE, 
         COUNT(COMPANY_NAME) AS NR_OF_MEMBER 
    FROM COMPANY
GROUP BY COMPANY_NAME, ENROLLMENT_FEE
ORDER BY NR_OF_MEMBER DESC;

但是,我只是想显示公司及其注册费,这是会员人数最多的。所以我通过添加where子句来完成以下操作:

  SELECT COMPANY_NAME, ENROLLMENT_FEE, 
         COUNT(COMPANY_NAME) AS NR_OF_MEMBER
    FROM COMPANY
GROUP BY COMPANY_NAME, ENROLLMENT_FEE
ORDER BY NR_OF_MEMBER DESC
   WHERE NR_OF_MEMBER = MAX(NR_OF_MEMBER);

但它表示 NR_OF_MEMBER 的无效标识符。

我只需要一行,只列出参与者最多的公司。

请帮忙。感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用ORDER BY以及仅获取一行的某种机制来获取具有最大值的一行。在MySQL中,这将是:

SELECT COMPANY_NAME, ENROLLMENT_FEE, COUNT(COMPANY_NAME) AS NR_OF_MEMBER
FROM COMPANY
GROUP BY COMPANY_NAME, ENROLLMENT_FEE
ORDER BY NR_OF_MEMBER DESC
LIMIT 1;

Oracle的语法略有不同。在Oracle 12+中,您可以使用ANSI标准FETCH FIRST 1 ROW ONLY而不是LIMIT 1

答案 1 :(得分:0)

SQL语句必须遵循一定的顺序。您当然不能在WHERE(或ORDER BY之后)拥有GROUP BY条款。以下是在Oracle中执行此操作的一种方法:

SELECT company_name, enrollment_fee, nr_of_member
     , RANK() OVER ( ORDER BY nr_of_member DESC ) AS rn
  FROM (
    SELECT company_name, enrollment_fee, COUNT(*) AS nr_of_member
      FROM company
     GROUP BY company_name, enrollment_fee
) WHERE rn = 1;

如果您只想要一行,而不是所有具有最小nr_of_member行的行,请使用ROW_NUMBER()代替RANK()