【问题标题】:PostgreSQL - how to sum only positive cumulative sums in totalPostgreSQL - 如何仅合计正累积总和
【发布时间】:2021-07-12 07:01:37
【问题描述】:



我尝试在包含客户结算历史的 PostgreSQL 数据库表中编写一个选择查询。查询结果应显示仅基于作为债务人的客户的金额总和(每个客户的所有发票金额总和大于零)。

在随附的示例中(下图) - 当我们从日期:10.06.2021 获取详细的结算历史记录时,您可以看到客户 A 的发票总金额为加 (+) 190000,因此应取该客户总和为总和。另一方面,客户 B 的发票金额总和为负 (-)266000,因此这不是债务人,应跳过。我尝试得出一个仅包含每个客户的正部分总和除以客户状态的总和,如下面的屏幕所示(预期结果)。

我试过这样的查询:

    select s.*, s.active+s.inactive total from
(select to_char(date_trunc('month', debt_date),'YYYY-MM'),
       greatest(sum(case when t.status = 'Active' then t.amount::numeric else 0 end),0) active,
       greatest(sum(case when t.status = 'Inactive' then t.amount::numeric else 0 end),0) inactive       
  from customers_settlement t
 group by 1) s  order by 1;

但它不起作用 - Excel 中的手动计算给出的结果与查询不同。我想有一些东西不见了:

over (partition by customer)

我相信像您这样的专业人士将能够快速帮助我。提前谢谢你!

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    我不完全确定这是否是您想要的,但您可以先按月份和客户分组,然后消除负面结果,然后再次求和:

    SELECT m,
           sum(active) AS "sum(Active)",
           sum(inactive) AS "sum(Inactive)",
           sum(active) + sum(inactive) AS "sum(Total)"
    FROM (SELECT to_char(date_trunc('month', debt_date),'YYYY-MM') AS m,
                 greatest(sum(t.amount) FILTER (WHERE t.status = 'Active'), 0) AS active,
                 greatest(sum(t.amount) FILTER (WHERE t.status = 'Inactive'), 0) AS inactive
          FROM customers_settlement AS t
          GROUP BY m, customer) AS subq
    GROUP BY m;
    

    【讨论】:

    • 你是大师!它完美地工作!非常感谢您的帮助!
    猜你喜欢
    • 2021-11-10
    • 2014-05-15
    • 2017-09-16
    • 2019-02-15
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多