using LINQ to find the cumulative sum of an array of numbers in C#

There’s a time for generality, and there’s a time for solving the problem actually posed. This is one of the latter times. If you want to make a method that turns a sequence of doubles into a sequence of partial sums, then just do that: public static IEnumerable<double> CumulativeSum(this IEnumerable<double> sequence) { double sum = … Read more

Calculate cumulative average (mean)

In analogy to the cumulative sum of a list I propose this: The cumulative average avg of a vector x would contain the averages from 1st position till position i. One method is just to compute the the mean for each position by summing over all previous values and dividing by their number. By rewriting … Read more

Cumulative sum over a set of rows in mysql

UPDATE MySQL 8.0 introduces “window functions”, functionality equivalent to SQL Server “window functions” (with partitioning and ordering provided by Transact-SQL OVER syntax), and Oracle “analytic functions”. MySQL Reference Manual 12.21 Window Functions https://dev.mysql.com/doc/refman/8.0/en/window-functions.html The answer provided here is an approach for MySQL versions prior to 8.0. ORIGINAL ANSWER MySQL doesn’t provide the type analytic function … Read more

Calculating Cumulative Sum in PostgreSQL

Basically, you need a window function. That’s a standard feature nowadays. In addition to genuine window functions, you can use any aggregate function as window function in Postgres by appending an OVER clause. The special difficulty here is to get partitions and sort order right: SELECT ea_month, id, amount, ea_year, circle_id , sum(amount) OVER (PARTITION … Read more

Create a Cumulative Sum Column in MySQL

MySQL 8.0/MariaDB supports windowed SUM(col) OVER(): SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum FROM tab; Output: ┌─────┬──────┬────────────────┐ │ id │ cnt │ cumulative_sum │ ├─────┼──────┼────────────────┤ │ 1 │ 100 │ 100 │ │ 2 │ 50 │ 150 │ │ 3 │ 10 │ 160 │ └─────┴──────┴────────────────┘ db<>fiddle