Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cumulative sum #40

Open
Roboroads opened this issue Jul 4, 2023 · 3 comments · May be fixed by #49
Open

Cumulative sum #40

Roboroads opened this issue Jul 4, 2023 · 3 comments · May be fixed by #49

Comments

@Roboroads
Copy link

Hi! It would be nice if there was a way to get a cumulative sum per time unit;

Lets say I'm building a bank app and need a trend of how full someones account is, which is calculated by the sum of their mutations. The 3rd time unit in the trend should be a sum of timeunit 1,2 and 3.

@avr
Copy link

avr commented Jul 19, 2023

@Roboroads - I was interested in this, too.

I made a new collection from loop over the data returned from a Trend's count.

Here's an example:

$data = Trend::model(User::class)
    ->between(
        start: $dates['startDate'],
        end: $dates['endDate'],
    )
    ->perDay()
    ->count();

$start = "some function to set the starting amount";

$totals = $data->map(function ($item, $key) use ($start, $data) {
    $item->total = $key === 0 ? $start + $item->aggregate : $data[$key - 1]->total + $item->aggregate;

    return $item;
});

This should give you a new attribute called "total" to use when you loop through $totals;

@Roboroads
Copy link
Author

Currenty - I am not using Trend for this specific one, just created my own mysql query since mysql is faster at aggregating;

Mutation::query()
  ->toBase()
  ->select([
      DB::raw('EXTRACT(YEAR_MONTH FROM created_at) AS month'),
      DB::raw('SUM(SUM(amount)) OVER (ORDER BY EXTRACT(YEAR_MONTH FROM created_at)) AS running_sum'),
  ])
  ->groupBy('month')
  ->orderBy('month')
  ->get()

@avr
Copy link

avr commented Jul 19, 2023

@Roboroads - how do you create the starting amount?

Like - if I'm looking at users for the last week, I want to start with the 1000 users who signed up before the start of this week. Using the DB, I've unioned in an extra row.

How would you handle the starting number?

@GeoSot GeoSot linked a pull request Dec 31, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants