Question

Say I have the following query...

SELECT key, MAX(count)
FROM (SELECT key, COUNT(*) count
      FROM table INNER JOIN table2 ON
           table.fld1 = table2.fld1
      GROUP BY key)

I am trying to get all possible keys and their MAX(count) but I don't see rownum working in this case because there is the possibility that two keys would share the same max COUNT(*) such as the following where both keys 200 and 202 share a max value...

key     COUNT(*)
200     5
202     5
308     3
309     2

In this case my queries output should be...

200     5
202     5

I am having trouble using the aggregate functions to accomplish this.

Was it helpful?

Solution 2

Try this (any database):

SELECT key, COUNT(*) count
FROM table
JOIN table2 ON table.fld1 = table2.fld1
GROUP BY key
HAVING count(*) = (
  select max(count) from (
    SELECT key, COUNT(*) count
    FROM table
    JOIN table2 ON table.fld1 = table2.fld1
    GROUP BY key) x)

Or with databases that support constant table expressions (oracle, sqlserver, etc):

WITH cte AS (
    SELECT key, COUNT(*) count
    FROM table
    JOIN table2 ON table.fld1 = table2.fld1
    GROUP BY key)
SELECT * FROM cte
WHERE count = (SELECT MAX(count) FROM cte)

Which should be a bit more efficient.

OTHER TIPS

I would approach this using analytic functions:

select key, cnt
from (select key, count(*) as cnt,
             dense_rank() over (order by count(*) desc) as seqnum
      from table t
      group by key
     ) t
where seqnum = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top