3

I have a users table with a timestamp when each user was created. I'd like to get the cumulative sum of users created per month.

I do have the following query which is working, but it's showing me the sum on a per day basis. I have a hard time going from this to a per month basis.

SELECT 
    created_at,
    sum(count(*)) OVER (ORDER BY created_at) as total
FROM users
GROUP BY created_at 

Expected output:

created_at  count
-----------------
2016-07  100
2016-08  150
2016-09  200
2016-10  500

Former reading:

4
  • Can you show us your expected output? There is more than one way to interpret your question. Commented Jan 22, 2018 at 7:36
  • Possible duplicate of Calculating Cumulative Sum in PostgreSQL Commented Jan 22, 2018 at 7:36
  • I have added the expected output. The referred question is not answering my question, as there is no per month grouping done there. Commented Jan 22, 2018 at 7:43
  • It's not 1:1 the same problem, but in the last code snippet of the accepted answer there you find almost exactly the answer you accepted here. Commented Jan 22, 2018 at 9:25

1 Answer 1

4

I'd take a two-step approach. First, use an inner query to count how many users were created each month. Then, wrap this query with another query that calculates the cumulative sum of these counts:

SELECT   created_at, SUM(cnt) OVER (ORDER BY created_at ASC)
FROM     (SELECT   TO_CHAR(created_at, 'YYYY-MM') AS created_at, COUNT(*) AS cnt
          FROM     users
          GROUP BY TO_CHAR(created_at, 'YYYY-MM')) t
ORDER BY 1 ASC;
Sign up to request clarification or add additional context in comments.

1 Comment

Much simpler than I thought, couldn't see the wood for the trees anymore :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.