【问题标题】:Cumulative sum SQL query for calculate sales contribution with Postgres使用 Postgres 计算销售贡献的累积和 SQL 查询
【发布时间】:2020-04-20 23:22:12
【问题描述】:

根据这张表,我需要计算每种产品对总销售额的贡献,并能够过滤这些产品占贡献的 80%

| prod_id | sales date | units_sold | total_price |
|---------+------------+------------+-------------|
|       1 | 2020-04-20 |         10 |      100.00 |
|       1 | 2020-04-19 |          2 |       20.00 |
|       2 | 2020-04-20 |          5 |       15.00 |
|       2 | 2020-04-19 |          5 |       15.00 |
|       3 | 2020-04-20 |         25 |       25.00 |
|       3 | 2020-04-19 |         25 |       25.00 |

考虑到总销售额等于 200 美元,Contribution % 的计算公式为:

  • prod_id=1 -> (100.00+20.00) / 200.00 = 0.6
  • prod_id=2 -> (15.00+15.00) / 200.00 = 0.15
  • prod_id=3 -> (25.00+25.00) / 200.00 = 0.25

Accumulate Contribution % 列是Contribution % 按此列从高到低排序的累加和

生成的查询应该类似于下面的查询

| prod_id | units_sold | total_price | Contribution % | Accumulate Contribution % |
|---------+------------+-------------+----------------+---------------------------|
|       1 |         12 |         120 |            0.6 |                       1.0 |
|       3 |         50 |          50 |           0.25 |                       0.4 |
|       2 |         10 |          30 |           0.15 |                      0.15 |

【问题讨论】:

  • 请解释最后两列的计算。
  • @GordonLinoff 我添加了解释。

标签: sql django postgresql cumulative-sum


【解决方案1】:

如果我理解正确,这是一个累积和的聚合:

select prod_id, sum(units_sold), sum(total_price),
       sum(total_price) / sum(sum(total_price)) over () as contribution_ratio,
       sum(total_price) / sum(sum(total_price)) over (order by sum(total_price) as accumulated
from t
group by prod_id
order by sum(total_price) desc;

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2020-11-04
    相关资源
    最近更新 更多