gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:33:28 26 4
gpt4 key购买 nike

我有一张 table

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

请帮忙解决上述问题。

最佳答案

只需将您的查询用作子查询:

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;

关于mysql - 如何使用 SQL-GROUP BY 查找重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com