有没有办法按出现频率排序mysql行?

时间:2011-12-15 04:43:15

标签: mysql sql-order-by

是否有按出现频率命令mysql行的方法?

1 个答案:

答案 0 :(得分:2)

SELECT n, count(*) as freq
FROM your_table
GROUP BY n
ORDER BY freq DESC;

更具体的例子:

SELECT n, count(*) as freq
FROM (
  SELECT 1 as n
  UNION ALL
  SELECT 2 as n
  UNION ALL
  SELECT 3 as n
  UNION ALL
  SELECT 3 as n
  UNION ALL
  SELECT 3 as n
  UNION ALL
  SELECT 2 as n) as your_table
GROUP BY n
ORDER BY freq DESC;

将返回:

n, freq
3, 3
2, 2
1, 1