sql >> Base de Datos >  >> RDS >> Mysql

Ordenar registros de consultas SQL por frecuencia

Asumiendo que quieres todo filas, pero ordenadas por la frecuencia de valores en alguna columna `col` , puedes hacer esto:

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;

que producirá

+----+--------+
| 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)