Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by month and counting rows for current and all previous months

PostgreSQL 13

Assuming a simplified table plans like the following, it can be assumed that there is at least 1 row for every month and sometimes multiple rows on the same day:

id first_published_at
12345678910 2022-10-01 03:58:55.118
abcd1234efg 2022-10-03 03:42:55.118
jhsdf894hld 2022-10-03 17:34:55.118
aslb83nfys5 2022-09-12 08:17:55.118

My simplified query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT TO_CHAR(plans.first_published_at, 'YYYY-MM') AS publication_date, COUNT(*)
FROM plans
WHERE plans.first_published_at IS NOT NULL
GROUP BY TO_CHAR(plans.first_published_at, 'YYYY-MM');

This gives me the following result:

publication_date count
2022-10 3
2022-09 1

But the result I would need for October is 4.

For every month, the count should be an aggregation of the current month and ALL previous months. I would appreciate any insight on how to approach this.

>Solution :

I would use your query as a CTE and run a select that uses cumulative sum as a window function.

with t as
(
 SELECT TO_CHAR(plans.first_published_at, 'YYYY-MM') AS publication_date, 
        COUNT(*) AS cnt
 FROM plans
 WHERE plans.first_published_at IS NOT NULL
 GROUP BY publication_date
)
select publication_date, 
       sum(cnt) over (order by publication_date) as "count"
from t
order by publication_date desc;

Demo on DB fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading