Erry215
Erry215

Reputation: 506

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();

Upvotes: 1

Views: 196

Answers (2)

nachospiu
nachospiu

Reputation: 2049

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();

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1270723

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

Upvotes: 1

Related Questions