SQL Group By with an Order By

前端 未结 6 2221
时光取名叫无心
时光取名叫无心 2020-11-28 03:08

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         


        
相关标签:
6条回答
  • 2020-11-28 03:21

    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
    
    0 讨论(0)
  • 2020-11-28 03:31

    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
    
    0 讨论(0)
  • 2020-11-28 03:34

    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.

    0 讨论(0)
  • 2020-11-28 03:37

    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
    
    0 讨论(0)
  • 2020-11-28 03:38

    You can get around this limit with the deprecated syntax: ORDER BY 1 DESC

    This syntax is not deprecated at all, it's E121-03 from SQL99.

    0 讨论(0)
  • 2020-11-28 03:47

    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
    
    0 讨论(0)
提交回复
热议问题