I have a table in Postgres named personal_profit
as shown below:
date | profit |
---|---|
2022-09-22 | 4000 |
2022-04-25 | 5000 |
2022-01-10 | 0 |
2022-02-14 | 0 |
2022-04-12 | 2000 |
2022-05-06 | 1000 |
2022-06-13 | 0 |
I want to get total profit ordered by month but starting with the month having profit greater than zero. The query below omits all the records with zero profit which doesn’t satisfy my condition. I just want the query to start from the month 04/2022.
Select distinct date_trunc('month', P.date) as profit_month, SUM(P.profit) as total_profit
from personal_profit P
group by profit_month
having SUM(P.profit) > 0
order by profit_month;
date | profit |
---|---|
2022-04 | 7000 |
2022-05 | 1000 |
2022-06 | 0 |
2022-09 | 4000 |
3
Answers
The condition "starting with the month having profit greater than zero" essentially means "skip the longest subsequence of zeros from the beginning". This can be achieved via selecting months with nonzero running total or via subquery. I consider the first way more comprehensible:
fiddle
Note the
running_total
expression should readsum(total_profit) over (order by profit_month)
in ideal world, however Postgres is not aware of aliases in sameselect
clause (even thegroup by <alias_from_select_clause>
is Postgres’ sugar and is unusual for other db vendors).you can check the month where you got first over 0 and use that to filter all values
fiddle
Since you want to start where, ordered by date, there is a non-zero value you can simply add that as a where criteria:
demo fiddle