SQL Order By Count

前端 未结 8 2205
北海茫月
北海茫月 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: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
    

提交回复
热议问题