简体   繁体   中英

how to query the max value of count

I try to get the max count value but error

this is my data

username   tool_id
___________________
user1         1
user1         2
user2         1
user3         3

I need to get the max count of tool_id

I use this code to get tool_count

SELECT tool_id, COUNT(tool_id) AS tool_count 
  FROM table 
 GROUP BY tool_id
tool_id   tool_count
_____________________
  1          2
  2          1
  3          1

and I use

SELECT tool_id,max(tool_count) 
 FROM
 (
  SELECT tool_id, COUNT(tool_id) AS tool_count 
    FROM table 
   GROUP BY tool_id
 )

to get max tool_count but it error

the result I need:

tool_id  tool_count
__________________
   1         2

You can try using order by desc with limit 1

SELECT tool_id, COUNT(tool_id) as tool_count 
from table 
group by tool_id
order by tool_count desc limit 1

if tool_id is primary_key remove GROUP BY from your query and you don't need to use of this command.

But if you get all of your rows of table at the same time with count, you need to group by a column that has similar data in all column, you can alter your table and add a column with default value that will not change ever.

It's better to get count in another query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM