163

I have a table of tags and want to get the highest count tags from the list.

Sample data looks like this

id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')

using

SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`

gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.

I tried this...

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

and I keep getting an "Invalid use of group function - ErrNr 1111"

What am I doing wrong?

I'm using MySQL 4.1.25-Debian

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
maxsilver
  • 4,524
  • 4
  • 28
  • 24

5 Answers5

243

In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:

SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
Scott Noyes
  • 2,556
  • 1
  • 14
  • 3
  • 10
    IMHO, this is the cleaner version than the selected answer. It's instantly clear what is ordered by. Of course, if its a quick script, that doesn't really matter. – JustAPoring Feb 04 '13 at 15:26
  • 1
    Although OP is using MySQL, this answer also worked for me in HSQL (Libreoffice built-in) – Arno Teigseth Nov 17 '15 at 02:39
55

MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.

You can get around this limit with the deprecated syntax:

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20

1, since it's the first column you want to group on.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
13

I don't know about MySQL, but in MS SQL, you can use the column index in the order by clause. I've done this before when doing counts with group bys as it tends to be easier to work with.

So

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

Becomes

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20
jerhinesmith
  • 15,214
  • 17
  • 62
  • 89
9

In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.

select 'Tag', counts.cnt
from
  (
  select count(*) as cnt, 'Tag'
  from 'images-tags'
  group by 'tag'
  ) counts
order by counts.cnt desc
JosephStyons
  • 57,317
  • 63
  • 160
  • 234
  • Seems to work for me in 10.1.14-MariaDB (MySQL-compatible). I thought I had to have `) as counts`, but it still worked without the `as` part. – Harry Pehkonen Aug 24 '17 at 14:08
-4

Try this query

 SELECT  data_collector_id , count (data_collector_id ) as frequency 
    from rent_flats 
    where is_contact_person_landlord = 'True' 
    GROUP BY data_collector_id 
    ORDER BY count(data_collector_id) DESC
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32