简体   繁体   中英

Order by count same values

I have a table like this:

ID |  Name  |  Group   

1    Mary      1    

2    Rose      1

3    Rose      2

4    Bob       2

5    Bob       2

I'd like to order them by Group, then by count(Name) and then rand() So with this result:

ID |  Name  |  Group   

4    Bob       2

5    Bob       2

3    Rose      2

2    Rose      1

1    Mary      1    

I wrote this query, but if I add count(Name) between group and rand, it gives me a bad result

SELECT * FROM table ORDER BY Group DESC, RAND();

Is this what you want?:

SELECT t.*
FROM table t
INNER JOIN (SELECT Name, count(*) AS countName FROM table GROUP BY Name) AS t1 ON t.Name = t1.Name
ORDER BY Group DESC, countName DESC, RAND();

You can use window functions in the order by :

order by count(*) over (partition by name) desc,
         name

Note: This doesn't randomize by name. If you really want that:

order by count(*) over (partition by name) desc,
         min(rand()) over (partition by name),
         name

In earlier versions, you can use a subquery:

order by (select count(*) from t t2 where t2.name = t.name) desc,
         name

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