【问题标题】:How to add column with accumulations of certain values from another column in SQL?如何在 SQL 中添加具有来自另一列的某些值的累积的列?
【发布时间】:2021-11-25 20:35:40
【问题描述】:

我有一张桌子:

     date           id  action     value
    2021-09-02      aa  income      500
    2021-09-02      aa  spending    500
    2021-09-02      aa  spending    45
    2021-09-03      aa  income      30
    2021-09-03      aa  income      30
    2021-09-03      aa  spending    25
    2021-09-04      b1  income      100
    2021-09-05      b1  income      500
    2021-09-05      b1  spending    500
    2021-09-05      b1  spending    45
    2021-09-06      b1  income      30
    2021-09-06      b1  income      30
    2021-09-07      b1  spending    25

如您所见,有两种类型的操作:“收入”和“支出”。我想为每个 id 在每个时刻添加“价值”累积的列。在每次行动“收入”之后,它必须按“收入”的价值增加,当有“支出”时,它必须按减少的价值减少。所以结果必须是这样的:

     date           id  action     value    saved 
    2021-09-02      aa  income      500      0
    2021-09-02      aa  spending    400      500
    2021-09-02      aa  spending    40       100
    2021-09-03      aa  income      30       60     
    2021-09-03      aa  income      30       90
    2021-09-03      aa  spending    25       120
    2021-09-04      b1  income      100      0
    2021-09-05      b1  income      500      100
    2021-09-05      b1  spending    500      600
    2021-09-05      b1  spending    45       100
    2021-09-06      b1  income      30       55
    2021-09-06      b1  income      30       85
    2021-09-07      b1  spending    25       115

如何做到这一点?我也不介意用 Python 来做

【问题讨论】:

  • 你如何定义排序?对符号使用带有大小写表达式的累积总和。

标签: python sql python-3.x dataframe presto


【解决方案1】:

假设该值可以转换为与支出重合的负值,则可以使用窗口函数计算运行总计,如下所示:

SELECT date,action,value,
  SUM(CASE WHEN action = 'spending' THEN -1*value ELSE value END) OVER (ORDER BY date)
  AS saved
FROM table;

您还可以从LearnSQL 的使用中找到此资源。

编辑:我已经更新了上面的查询以包含一个嵌套在窗口函数中的 CASE;即将值转换为类别为“支出”的负值,然后计算运行总计。

【讨论】:

  • 谢谢,但它最初不会为“保存”带来 0
【解决方案2】:
select *
    , case when row_number() over (order by date) = 1 then 0 
      else sum(case when action = 'spending' then -value else value end) over (order by date) end as save 
from table

【讨论】:

  • 谢谢,但它最初不会为“保存”带来 0
  • @french_fries 查看更新的答案
猜你喜欢
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 2021-09-27
  • 2015-07-04
相关资源
最近更新 更多