如何使用SQL-GROUP BY查找重复行

时间:2014-11-25 15:58:39

标签: mysql group-by

我有一张桌子

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

请帮助解决上述问题。

1 个答案:

答案 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;