1

I have this table:

id
entry_date (timestamp)
exit_date (timestamp)

I need to show the cumulative difference per every day. Actually average, but let at least be just cumulative.

So the output will look like this:

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

Meaning

Year month day cummulative_sum(exit_date-entry_date).

I have checked similar threads:

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

But none of the solutions worked for me. I am becoming desperate to do this with SQL alone. But the tasks sounds so simple that it's hard to believe the solution is a difficult to find.

1 Answer 1

0

You might be able to work something more efficient but I believe this is something to get you going. And your explanation is not incredible clear so you might want to work on providing some sample data to clarify what you need.

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

Replace T with the name of your table. Also I used a cast to strip away the time but I'm not sure that's actually valid in MySQL.

The average of days (not including any dates not represented by an entry or exit) is then easy as well:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.