Angenommen, Sie wollen alle Zeilen, aber sortiert nach der Häufigkeit der Werte in einigen Spalten `col`
, können Sie Folgendes tun:
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;
die produzieren wird
+----+--------+
| 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)