Skip to content
Advertisement

how to filter aggregate query ordered by date

I need to retrieve aggregate information (by means of SUM) on the basis of two separate dates – created_at and erased_at.

The requirement is as follows:

Column Description
Month Month as YYYY-MM
Active_users Total number of unique users in the Month. The users have not been erased during or before the Month.

An example set of data in a “users” table is as below:

The particular monthly sums of users created_at in a given month can be made by means of:

(The same may be done for erased_at, of course.)

However, how do I formulate a query to present the number of active users within any month, who have already been created (not necessarily within the particular month) and who have not been erased at the time?

I’ve tried various subqueries and joins and I’m obviously beyond my paygrade on it and I do understand this probably is a student-level kind of question.

Please, help.

(I’m on Postgresql 9.6 in case it needs to be that advanced.)

Advertisement

Answer

One method generates the months and then uses JOIN and GROUP BY:

Note: This is users active at any point during the month, which is how I interpret your question. You can tweak the query if you really mean:

  • Users active for the entire month.
  • Users active on the first day of the month.
  • Users active on the last day of the month.

EDIT:

You can use the dates in the data using:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement