SQL嵌套聚合函数MAX(COUNT(*))

时间:2014-04-07 14:23:51

标签: sql oracle select aggregate-functions

我试图选择max(行数)。 这是我的两个SELECT

变种
SELECT MAX(COUNT_OF_ENROLEES_BY_SPEC) FROM
(SELECT D.SPECCODE, COUNT(D.ENROLEECODE) AS COUNT_OF_ENROLEES_BY_SPEC
 FROM DECLARER D
 GROUP BY D.SPECCODE
);

SELECT S.NAME, MAX(D.ENROLEECODE)
  FROM SPECIALIZATION S
    CROSS JOIN DECLARER D WHERE S.SPECCODE = D.SPECCODE
  GROUP BY S.NAME
  HAVING MAX(D.ENROLEECODE) = 
  ( SELECT MAX(COUNT_OF_ENROLEES_BY_SPEC) FROM
      ( SELECT D.SPECCODE, COUNT(D.ENROLEECODE) AS COUNT_OF_ENROLEES_BY_SPEC
        FROM DECLARER D
        GROUP BY D.SPECCODE
      )
  );

第一个工作正常,但我想用#34; HAVING"重写它。就像在我的第二个变体中,再添加一列。但现在第二个变量不输出结果中的任何数据,只是空列。 我该如何解决?谢谢你!)

1 个答案:

答案 0 :(得分:0)

此查询基于评论中给出的描述和一些建议,因此可能是错误的:

select                   -- 4. Join selected codes with specializations
  S.Name,
  selected_codes.spec_code,
  selected_codes.count_of_enrolees_by_spec   
from 
  specialization S,
  ( 
    select               -- 3. Filter records with maximum popularity only
      spec_code, 
      count_of_enrolees_by_spec
    from (
      select             -- 2. Count maximum popularity in separate column
        spec_code, 
        count_of_enrolees_by_spec,
        max(count_of_enrolees_by_spec) over (partition by null) max_count
      from (
        SELECT           -- 1. Get list of declarations and count popularity
          D.SPECCODE           AS SPEC_CODE, 
          COUNT(D.ENROLEECODE) AS COUNT_OF_ENROLEES_BY_SPEC
        FROM DECLARER D
        GROUP BY D.SPECCODE
      )
    )
    where count_of_enrolees_by_spec = max_count
  )
    selected_codes
where 
  S.SPECCODE = selected_codes.spec_code

同样查询未经测试,可能会出现一些语法错误。