Question

I'm trying to select max(count of rows). Here is my 2 variants of 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
      )
  );

The first one is working OK, but I want to rewrite it using "HAVING" like in my second variant and add there one more column. But now 2nd variant don't output any data in results, just empty columns. How can I fix it ? Thank YOU!)

Was it helpful?

Solution

This query based on description given in comments and some suggestions, so it may be wrong:

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

Also query not tested and some syntax errors are possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top