Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frequency based sort in sql [duplicate]

I have a problem with sorting sql tables.

I have this:

+------+------+
| col1 | col2 |
+------+------+
| a    |    1 |
| b    |   3  |
| c    |    4 |
| d    |    3 |
| e    |    2 |
| f    |    2 |
| g    |    2 |
| h    |    1 |
+------+------+

And i need to have this:

+------+------+
| col1 | col2 |
+------+------+
| e    |    2 |
| f    |    2 |
| g    |    2 |
| a    |    1 |
| h    |    1 |
| b    |    3 |
| d    |    3 |
| c    |    4 |
+------+------+

I tried with COUNT(), but it work only with GROUP OF that's why it isn't what i need.

Sorry for my bad english and thanks for all responses.

like image 317
E-cma Avatar asked Dec 02 '25 17:12

E-cma


1 Answers

If database supports OVER clause then it is quite simple:

SELECT t.id, t.value
FROM t
ORDER BY count(*) over (partition by value) DESC

See SQL Fiddle - http://sqlfiddle.com/#!6/ce805/3

like image 53
Bulat Avatar answered Dec 05 '25 07:12

Bulat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!