Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select MAX(COUNT)

Tags:

sql

I'm trying to select the user who has the MAX microposts count:

SELECT "name", count(*) FROM "users" 
  INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
  GROUP BY users.id

and this returns

"Delphia Gleichner";15
"Louvenia Bednar IV";10
"Example User";53
"Guadalupe Volkman";20
"Isabella Harvey";30
"Madeline Franecki II";40

But I want to select only "Example User";53, (user who has MAX microposts count)

I tried to add HAVING MAX(count*) but this didn't work.

like image 212
Mykhailo Rybak Avatar asked Sep 30 '13 07:09

Mykhailo Rybak


People also ask

Can you do a max count in SQL?

And the short answer to the above question is, no. You can't. It is not possible to nest aggregate functions.

How do you find the highest count in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How do you SELECT the top 3 maximum value in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.

What is Count Max?

Count Max (Italian:Il conte Max) is a 1957 Italian-Spanish comedy film directed by Giorgio Bianchi and starring Alberto Sordi, Vittorio De Sica and Anne Vernon. It is a remake of the 1937 film Il signor Max in which De Sica had played the title role. This film was itself remade in 1991.


2 Answers

I'd try with a ORDER BY max DESC LIMIT 1, where maximum is the count(*) field. Something like:

SELECT "name", count(*) maximum FROM "users" 
   INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id 
ORDER BY maximum DESC 
LIMIT 1

I dont' have mysql available now, so I'm doing this on the paper (and it might not work), but it's just an orientation.

like image 92
opalenzuela Avatar answered Sep 30 '22 03:09

opalenzuela


SELECT x.name, MAX(x.count)
FROM (
 SELECT "name", count(*)
  FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
  GROUP BY users.id
) x
GROUP BY x.name
like image 31
Nikhil Avatar answered Sep 30 '22 03:09

Nikhil