You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何从首个盈利月份开始统计月度总利润

问题解决

原表数据

dateprofit
2022-09-224000
2022-04-255000
2022-01-100
2022-02-140
2022-04-122000
2022-05-061000
2022-06-130

原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;

逻辑说明

  1. monthly_profit:按月份聚合所有数据的总利润,保留所有存在记录的月份(包括零利润)。
  2. first_positive_month:找出第一个总利润大于0的月份作为统计起始点。
  3. 最终筛选出起始月份及之后的所有月份数据,格式化为YYYY-MM日期格式并排序。

执行结果

dateprofit
2022-047000
2022-051000
2022-060
2022-094000

内容的提问来源于stack exchange,提问作者Ricky Vikram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:53:27