MYSQL对计数结果进行计数和分组

时间:2014-01-09 14:43:21

标签: mysql mysqli count group-by

我希望计算每封电子邮件的总订单数量,然后将结果的频率分组

如果以下查询

SELECT COUNT(*) as total
FROM orders
GROUP BY email 
ORDER BY total DESC

给我

|--TOTAL--|
|    6    |
|    6    |
|    6    |
|    5    |
|    5    |
|    5    |
|    4    |
|    4    |
|    3    |
|    2    |
|---------|

我怎样才能得到这个结果

|--TOTAL--|--COUNT--|
|    6    |    3    |
|    5    |    3    |
|    4    |    2    |
|    3    |    1    |
|    2    |    1    |
|-------------------|

我基本上想要数数

干杯

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT total, COUNT(total) AS frequency
FROM (
  SELECT COUNT(*) as total
  FROM orders
  GROUP BY email
) t
GROUP BY total
ORDER BY total DESC

基本上,您可以通过将原始查询转换为子查询来执行其他聚合。

答案 1 :(得分:0)

您可以将查询用作子查询:

SELECT total, COUNT(*)
FROM (
  SELECT COUNT(*) as total
  FROM orders
  GROUP BY email
) t
GROUP BY total
ORDER BY COUNT(*) DESC