【问题标题】:Aggregating Data between the occurrence of two events在两个事件发生之间聚合数据
【发布时间】:2021-08-18 20:57:58
【问题描述】:

我有这样的数据:

Date Type Amount
1/1/21 Load 40.00
1/2/21 Spend -20.00
1/3/21 Withdraw -10.00
1/4/21 Load 40.00
1/5/21 Spend -20.00
1/5/21 Spend -15.00
1/6/21 Load 40.00

我想做的是得到这样的输出:

Load Date Type Amount
1/1/21 Spend -20.00
1/1/21 Withdraw -10.00
1/4/21 Spend -35.00

我想在 load 类型的两行之间汇总分配给每个交易 type 的金额。

我将如何在 SQL 中执行此操作?

【问题讨论】:

  • 哪个版本的 MySQL? (为什么这也被标记为 vertica?)

标签: mysql sql


【解决方案1】:

如果我理解正确,您可以创建一个累积的负载计数,然后聚合:

select min(load_date), type, sum(amount)
from (select t.*,
             sum(case when type = 'load' then 1 else 0 end) over (order by load_date) as load_grp
      from t
     ) t
where type <> 'load'
group by load_grp;

也就是说,您的结果看起来更像是按日期和类型汇总的非加载事件:

select load_date, type, sum(amount)
from t
where type <> 'load'
group by load_date, type;

【讨论】:

  • 谢谢!累积负载计数的想法非常有帮助。使用它作为哪个事务类型属于特定负载的标识符允许我根据需要进行聚合!
猜你喜欢
  • 2015-03-22
  • 2019-06-25
  • 2023-03-27
  • 2020-03-12
  • 1970-01-01
  • 2018-11-23
  • 2015-12-17
  • 2012-04-26
  • 1970-01-01
相关资源
最近更新 更多