Ако приемем, че искате всички редове, но подредени по честотата на стойностите в някаква колона `col`
, можете да направите това:
CREATE TABLE tbl (id SERIAL, col VARCHAR(16));
-- INSERT so that `id` does not match frequency of values under `col`
INSERT INTO tbl (col) VALUES ('value1'), ('value2'), ('value3'),
('value1'), ('value2'), ('value3'),
('value1'), ('value2'),
('value1'),
('value1');
SELECT id, tbl.col
FROM tbl
INNER JOIN ( SELECT col, COUNT(1) AS freq
FROM tbl
GROUP BY 1) derived
USING (col)
ORDER BY derived.freq DESC;
което ще произведе
+----+--------+
| id | col |
+----+--------+
| 4 | value1 | <-- highest incidence
| 7 | value1 |
| 1 | value1 |
| 9 | value1 |
| 10 | value1 |
| 5 | value2 |
| 8 | value2 |
| 2 | value2 |
| 6 | value3 | <-- lowest incidence
| 3 | value3 |
+----+--------+
10 rows in set (0.00 sec)