In postgresql, how to get cumulative count? I wanted to get a cumulative count of customers enrolled between 01-01 and 02-01, 01-01 and 03-01, 01-01 and 04-01 etc.,
Not sure if we can do for loop like in Python? I checked out a few for loop posts but am lost
select count(distinct customer)
from mytable
where enrollment_dt between '2023-01-01' and '2023-xx-01'
(this xx will increase by 1 month in each run, like 02-01, 03-01, 04-01...)
so ideally the output should be like:
date | count |
---|---|
01/01-02/01 | 10 |
01/01-03/01 | 12 |
01/01-04/01 | 15 |
01/01-05/01 | 19 |
… | … |
2
Answers
Looks like you need a window function to do a running sum over the normal aggregation.
It is not quite clear what exactly you want to do. I took a blind guess and could offer solutions for two possible options. To test it – lets assume that your sample data could be like this:
There are months with and without newly enrolled costumers. So you maybe want to select just the rows with new enrollments:
… on the other hand maybe you want to select all the months in certain period regardless new enrollments…
.. for this you will need a sort of calendar of months in period…
… the calendar data should be joined to the sql from Option 1. (Left Join) handling the Null values…
See the fiddle here.