【问题标题】:How to query distribution with MySQL如何使用 MySQL 查询分布
【发布时间】:2020-08-31 15:46:55
【问题描述】:

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

表格

--------------------
|dates | event_count|
---------------------
|03/02 |  4         |
|03/03 |  3         |
|03/04 |  5         |
|03/05 |  2         |
|03/06 |  2         |
|03/06 |  5         |
---------------------

结果表

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

感谢任何建议!谢谢。

【问题讨论】:

    标签: mysql sql count left-join recursive-query


    【解决方案1】:

    你只是想要聚合吗?

    select event_count, count(*) frequency
    from mytable 
    group by event_count
    

    另一方面,如果您想要所有可能的event_count 的行,即使它们没有出现在表中,那么它有点不同。一种方法是使用递归查询来生成值,然后将表带上left join

    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
    

    递归查询仅在 MySQL 8.0 中可用。

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多