PostgreSQL中如何从首个盈利月份开始统计月度总利润
问题解决
原表数据
| 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 |
原SQL问题
你当前的SQL用having SUM(P.profit) > 0过滤了所有零利润月份,同时未限定统计起始月份,无法满足需求。
修正后的SQL
WITH monthly_profit AS ( SELECT date_trunc('month', date)::date AS profit_month, SUM(profit) AS total_profit FROM personal_profit GROUP BY date_trunc('month', date)::date ), first_positive_month AS ( SELECT MIN(profit_month) AS start_month FROM monthly_profit WHERE total_profit > 0 ) SELECT TO_CHAR(profit_month, 'YYYY-MM') AS date, total_profit AS profit FROM monthly_profit, first_positive_month WHERE profit_month >= start_month ORDER BY profit_month;
逻辑说明
monthly_profit:按月份聚合所有数据的总利润,保留所有存在记录的月份(包括零利润)。first_positive_month:找出第一个总利润大于0的月份作为统计起始点。- 最终筛选出起始月份及之后的所有月份数据,格式化为
YYYY-MM日期格式并排序。
执行结果
| date | profit |
|---|---|
| 2022-04 | 7000 |
| 2022-05 | 1000 |
| 2022-06 | 0 |
| 2022-09 | 4000 |
内容的提问来源于stack exchange,提问作者Ricky Vikram
相关产品推荐
相关产品推荐

