【问题标题】:cumulative sum grouped by day按天分组的累积总和
【发布时间】:2015-09-11 10:48:40
【问题描述】:

我有这张桌子:

id
entry_date (timestamp)
exit_date (timestamp)

我需要显示每天的累积差异。实际上是平均的,但至少是累积的。

所以输出将如下所示:

2015 1 1 33
2015 1 3 56
2015 2 4 77
2015 3 12 123

意义

Year month day cummulative_sum(exit_date-entry_date).

我检查过类似的主题:

MySQL cumulative sum grouped by date

Cumulative sum over a set of rows in mysql

Optimal query to fetch a cumulative sum in MySQL

Create a Cumulative Sum Column in MySQL

MYSQL request | GROUP BY DAY

但是没有一个解决方案对我有用。我越来越不顾一切地只用 SQL 来做到这一点。 但是这些任务听起来很简单,以至于很难相信解决方案很难找到。

【问题讨论】:

    标签: mysql group-by sum average


    【解决方案1】:

    你也许可以做一些更有效率的事情,但我相信这会让你继续前进。而且您的解释不是很清楚,因此您可能需要提供一些示例数据来阐明您的需求。

    select
        event_date,
        (
            select sum(+1) from T as t2 where cast(t2.entry_date as date) <= d.event_date +
            select sum(-1) from T as t3 where cast(t3.exit_date  as date) <= d.event_date
        ) as cumulative_total /* at end of day */
    from (
        select cast(entry_date as date) as event_date from T union all
        select cast(exit_date  as date) from T
    ) as d
    group by event_date
    

    将 T 替换为您的表的名称。我还使用演员表来消除时间,但我不确定这在 MySQL 中是否有效。

    平均天数(不包括任何未由进入或退出表示的日期)也很容易:

    select avg(cumulative_total) as average_per_day
    from (
        select
            (
                select sum(+1) from T as t2 where cast(t2.entry_date as date) <= d.event_date +
                select sum(-1) from T as t3 where cast(t3.exit_date  as date) <= d.event_date
            ) as cumulative_total /* at end of day */
        from (
            select cast(entry_date as date) as event_date from T union all
            select cast(exit_date  as date) from T
        ) as d
        group by event_date
    ) as d2
    

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 2019-12-01
      • 1970-01-01
      • 2014-07-13
      • 2021-06-18
      • 2018-05-30
      • 2020-12-23
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多