Money_Badger
Money_Badger

Reputation: 567

SQL aggregate totals for each previous record

Is it possible to write an SQL query which aggregates all of the previous records, i.e. shows the timeline which increases with each record. This is not aggregating each record based on a logical test but aggregating using the current total.

For example for data

| date | new_users |
|------|-----------|
| day0 | 2         |
| day1 | 1         |
| day2 | 3         |

I would like to get

| date | total_users|
|------|------------|
| day0 | 2          |
| day1 | 3          |
| day2 | 6          |

Upvotes: 0

Views: 52

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269593

I think you want a cumulative sum:

select date,
       sum(new_users) over (order by date) as total_users
from t;

Upvotes: 2

Related Questions