我有一张桌子
+----+------------+
| id | day |
+----+------------+
| 1 | 2006-10-08 |
| 2 | 2006-10-08 |
| 3 | 2006-10-09 |
| 4 | 2006-10-09 |
| 5 | 2006-10-09 |
| 5 | 2006-10-09 |
| 6 | 2006-10-10 |
| 7 | 2006-10-10 |
| 8 | 2006-10-10 |
| 9 | 2006-10-10 |
+----+------------
我希望按频率及其计数进行分组,例如: -
由于日期2006-10-08
出现两次,因此频率2
并且只有一个日期出现两次,因此总日期为1
。
另一个例如: -
2006-10-10
和2006-10-09
都出现了4次,因此频率4
和频率为4的总日期为2
。
以下是预期的输出。
+----------+--------------------------------+
| Freuency | Total Dates with frequency N |
+----------+--------------------------------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
+----------+--------------------------------+ and so on till the maximum frequency.
我尝试的是以下内容: -
select day, count(*) from test GROUP BY day;
它返回每个日期的频率,即
+------------+----------+
| day | count(*) |
+------------+----------+
| 2006-10-08 | 2 |
| 2006-10-09 | 4 |
| 2006-10-09 | 4 |
+------------+----------+
请帮助解决上述问题。
答案 0 :(得分:1)
只需将您的查询用作子查询:
select freq, count(*)
from (select day, count(*) as freq
from test
group by day
) d
group by freq;
如果您想获得0
值,那么您必须更加努力。数字表很方便(如果有的话)或者您可以这样做:
select n.freq, count(d.day)
from (select 1 as freq union all select 2 union all select 3 union all select 4
) n left join
(select day, count(*) as freq
from test
group by day
) d
on n.freq = d.freq
group by n.freq;