-1
**castID**
nm0000116
nm0000116
nm0000116
nm0000116
nm0000116
nm0634240
nm0634240
nm0798899

This is my table (created as a view). Now I want to list the castID which has the most count (in this case which is nm0000116, and how many occurences/count it has in this table ( should be 5 times) and I'm not quite sure which query to use

Andriy M
  • 76,112
  • 17
  • 94
  • 154
user3601148
  • 175
  • 1
  • 9
  • Please clarify your specific problem by providing the code you've tried. As it's currently written, it’s hard to tell exactly what you're asking. – Kermit May 05 '14 at 16:24

3 Answers3

1
SELECT 
  MAX(E),
  castId
FROM 
 (SELECT COUNT(castId) AS E,castId FROM [directors winning movies list] GROUP BY castId) AS t
potashin
  • 44,205
  • 11
  • 83
  • 107
1

try

Select CastId, count(*) countOfCastId
From table 
Group By CastId
Having count(*)
    = (Select Max(cnt)
       From (Select count(*) cnt
             From table
             Group By CastId) z)
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

You could just return the topmost count using LIMIT:

SELECT   castID,
         COUNT(*) AS Cnt
FROM     atable
GROUP BY castID
ORDER BY Cnt DESC
LIMIT    1
;

However, if there can be ties, the above query would return only one row. If you want all the "winners", you could take the count from the above query as a scalar result and compare it against all the counts to return only those that match:

SELECT   castID,
         COUNT(*) AS Cnt
FROM     atable
GROUP BY castID
HAVING   COUNT(*) = (
                        SELECT   COUNT(*)
                        FROM     atable
                        GROUP BY castID
                        ORDER BY Cnt DESC
                        LIMIT    1
                    )
;

(Basically, same as Charles Bretana's approach, it just derives the top count differently.)

Alternatively, you could use a variable to rank all the counts and then return only those that have the ranking of 1:

SELECT castID,
       Cnt
FROM   (
          SELECT   castID,
                   COUNT(*) AS Cnt,
                   @r := IFNULL(@r, 0) + 1 AS r
          FROM     atable
          GROUP BY castID
          ORDER BY Cnt DESC
       ) AS s
WHERE r = 1
;

Please note that with the above method the variable must either not exist or be pre-initialised with a 0 or NULL prior to running the query. To be on the safe side, you could initialise the variable directly in your query:

SELECT s.castID,
       s.Cnt
FROM   (SELECT @r := 0) AS x
CROSS JOIN
       (
          SELECT   castID,
                   COUNT(*) AS Cnt,
                   @r := @r + 1 AS r
          FROM     atable
          GROUP BY castID
          ORDER BY Cnt DESC
       ) AS s
WHERE s.r = 1
;
Community
  • 1
  • 1
Andriy M
  • 76,112
  • 17
  • 94
  • 154