¿Cómo cuento el póster superior en una categoría específica en MySQL?

Current DB for update_log

ID   CatName  UserID
-----------------------------
1    book     2
2    book     2
3    book     1
4    car      1
5    car      2
6    car      3
7    car      1
8    house    2
9    house    1
10   house    1

What is the correct statement to count CatName y UserID then GROUP BY CatName y UserID

SELECT 
    CatName,
        UserID,
    COUNT(CatName) as CategoryName,
    COUNT(UserID) as MostUser   
    FROM update_log 
        GROUP BY CatName
        ORDER BY COUNT(CatName) DESC

I want the result should be like this

Category Name  Most Posted by
-----------------------------
book           2
car            1
house          1

preguntado el 08 de noviembre de 11 a las 18:11

1 Respuestas

This should work, although I feel like there must be a better/more succinct way of doing this:

SELECT
 dt1.CatName, 
 dt1.UserId
FROM
 ( SELECT COUNT(*) as num_posts, CatName, UserID
   FROM update_log
   GROUP BY CatName, UserID) as dt1
 INNER JOIN (
  SELECT MAX(num_posts) as max_posts, CatName
  FROM (
   SELECT COUNT(*) as num_posts, CatName, UserID
   FROM update_log
   GROUP BY CatName, UserID) as dt2
  GROUP BY CatName) as dt3 
 ON ( dt3.CatName = dt1.CatName 
      AND dt1.num_posts = dt3.max_posts)

respondido 09 nov., 11:00

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.