Skip to content
Advertisement

PostgreSQL, summing multiple date columns over multiple rows

Let’s assume the following table:

Now I want to know the total amount of times a month is set in any row or column combined as long as the date is in the future.

Right now I have:

This works and returns the right result, yet it is rather bloated and it returns me a single row with a column for every month. As in real life this query is a bit more complex and I would rather have a result that would give me a row for each month (So I can add more fields to every monthly row)

Is there any thing I am missing, any way I can improve this?

Advertisement

Answer

Do you want a lateral join?

Truncating the date to the first day of the month would seem more useful that extracting the month (if your data spreads over several years in the future, the result do differ). But if you do mean extracting the month, then:

Finally, if you want a row for each month, even those that have no timestamp in the future, then:

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