すべてが必要だと仮定します 行ですが、一部の列の値の頻度順に並べられています`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)