如何使用MySQL查询分布

如何使用MySQL查询分布,mysql,sql,count,left-join,recursive-query,Mysql,Sql,Count,Left Join,Recursive Query,我正在寻找使用MySQL查询频率分布的方法。我有一个表,其中有一列记录了日期和另一个事件的发生。理想的输出是一个表,表中的事件计数值按升序排列,并具有相应的频率 桌子 结果表 ------------------------ |event_count | frequency| ------------------------ |0 |0 | |1 |0 | |2

我正在寻找使用MySQL查询频率分布的方法。我有一个表,其中有一列记录了日期和另一个事件的发生。理想的输出是一个表,表中的事件计数值按升序排列,并具有相应的频率

桌子

结果表

    ------------------------
    |event_count | frequency|
    ------------------------
    |0           |0         |
    |1           |0         |
    |2           |2         |
    |3           |1         |
    |4           |1         |
    |5           |2         |
    -------------------------

任何建议都将不胜感激!谢谢。

您只需要聚合吗

select event_count, count(*) frequency
from mytable 
group by event_count
另一方面,如果您想要所有可能的事件计数的行,即使它们没有出现在表中,那么它有点不同。一种方法使用递归查询生成值,然后将表与左联接:

递归查询仅在MySQL 8.0中可用

select event_count, count(*) frequency
from mytable 
group by event_count
with recursive cte as (
    select 0 event_count, max(event_count) max_event_count from mytable
    union all
    select event_count + 1 from cte where event_count < max_event_count
)
select c.event_count, count(t.event_count) frequency
from cte c
left join mytable t on t.event_count = c.event_count
group by c.event_count