SQL Order By Count

前端 未结 8 2162
北海茫月
北海茫月 2020-12-01 02:38

If I have a table and data like this:

ID |  Name  |  Group   

1    Apple     A    

2    Boy       A

3    Cat       B

4    Dog       C

5    Elep      C

         


        
相关标签:
8条回答
  • 2020-12-01 03:00

    Below gives me opposite of what you have. (Notice Group column)

    SELECT
        *
    FROM
        myTable
    GROUP BY
        Group_value,
        ID
    ORDER BY
        count(Group_value)
    

    Let me know if this is fine with you...

    I am trying to get what you want too...

    0 讨论(0)
  • 2020-12-01 03:03

    ...none of the other answers seem to do what the asker asked.

    For table named 'things' with column 'group':

    SELECT
      things.*, counter.count
    FROM
      things
    LEFT JOIN (
      SELECT
        things.group, count(things.group) as count
      FROM
        things
      GROUP BY
        things.group
    ) counter ON counter.group = things.group
    ORDER BY
      counter.count ASC;
    

    which gives:

    id | name  | group | count 
    ---------------------------
    3  | Cat   | B     | 1
    1  | Apple | A     | 2
    2  | Boy   | A     | 2
    4  | Dog   | C     | 3
    5  | Elep  | C     | 3
    6  | Fish  | C     | 3
    
    0 讨论(0)
  • 2020-12-01 03:04

    Try :

    SELECT count(*),group FROM table GROUP BY group ORDER BY group
    

    to order by count descending do

    SELECT count(*),group FROM table GROUP BY group ORDER BY count(*) DESC
    

    This will group the results by the group column returning the group and the count and will return the order in group order

    0 讨论(0)
  • 2020-12-01 03:04
    SELECT * FROM table 
    group by `Group`
    ORDER BY COUNT(Group)
    
    0 讨论(0)
  • 2020-12-01 03:07
    SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group
    

    or to order by the count

    SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC
    
    0 讨论(0)
  • Try using below Query:

    SELECT
        GROUP,
        COUNT(*) AS Total_Count
    FROM
        TABLE
    GROUP BY
        GROUP
    ORDER BY
        Total_Count DESC
    
    0 讨论(0)
提交回复
热议问题