删除重复的item\u id,但在mysql中向初始行添加价格

to94eoyn  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(234)

版本=mysql 8.0
mre公司:

  1. create table test_table(
  2. item_id int,
  3. price decimal,
  4. transaction_time datetime
  5. );
  6. insert into test_table(item_id, price, transaction_time)
  7. Values (1, 5500, "2020-01-01 00:11:11")
  8. , (1, 1000, "2020-01-07 01:11:11")
  9. , (3, 1100, "2020-01-06 18:10:10")
  10. , (3, 7700, "2020-01-03 18:10:10")
  11. , (4, 1900, "2020-01-02 12:00:11");

使用窗口功能获取我运行的每个项目的累计价格:

  1. select *
  2. , sum(price) over(partition by item_id) as cum_fee
  3. from test_table;

输出:

  1. item_id price transaction_time cum_fee
  2. 1 5500 2020-01-01 00:11:11 6500
  3. 1 1000 2020-01-07 01:11:11 6500
  4. 3 1100 2020-01-06 18:10:10 8800
  5. 3 7700 2020-01-03 18:10:10 8800
  6. 4 1900 2020-01-02 12:00:11 1900

现在我想去掉重复的项目标识,之所以添加窗口功能,是因为我想去掉重复的项目标识,但要保留它们的累计价格“累计费用”。
我最初的尝试是在最后按项目\u id分组:

  1. select *
  2. , sum(price) over(partition by item_id) as cum_fee
  3. from test_table
  4. group by item_id;

这似乎是先按项目\u id分组,然后运行窗口功能输出:

  1. item_id price transaction_time cum_fee
  2. 1 5500 2020-01-01 00:11:11 5500
  3. 3 1100 2020-01-06 18:10:10 1100
  4. 4 1900 2020-01-02 12:00:11 1900

我知道有人在比较groupby和windowing函数,这可能意味着我们使用其中一个,而不是两个?是真的吗?
是的,实现我的目标的替代方法是什么?

u1ehiz5o

u1ehiz5o1#

你好像想要聚合。也许是这个?

  1. select item_id, min(price), min(transaction_time), sum(price)
  2. from test_table
  3. group by item_id;

窗口函数不会更改行数。那是什么 group by 做。

相关问题