我有这张表:
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
但是这些解决方案都不适合我。我越来越渴望仅用 SQL 来完成此任务。 但这些任务听起来如此简单,以至于很难相信解决方案很难找到。
最佳答案
你也许可以做一些更有效率的事情,但我相信这是让你继续前进的东西。而且您的解释并不清晰,因此您可能需要提供一些示例数据来阐明您的需求。
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
关于mysql - 按天分组的累计总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31040022/