版本=mysql 8.0
mre公司:
create table test_table(
item_id int,
price decimal,
transaction_time datetime
);
insert into test_table(item_id, price, transaction_time)
Values (1, 5500, "2020-01-01 00:11:11")
, (1, 1000, "2020-01-07 01:11:11")
, (3, 1100, "2020-01-06 18:10:10")
, (3, 7700, "2020-01-03 18:10:10")
, (4, 1900, "2020-01-02 12:00:11");
使用窗口功能获取我运行的每个项目的累计价格:
select *
, sum(price) over(partition by item_id) as cum_fee
from test_table;
输出:
item_id price transaction_time cum_fee
1 5500 2020-01-01 00:11:11 6500
1 1000 2020-01-07 01:11:11 6500
3 1100 2020-01-06 18:10:10 8800
3 7700 2020-01-03 18:10:10 8800
4 1900 2020-01-02 12:00:11 1900
现在我想去掉重复的项目标识,之所以添加窗口功能,是因为我想去掉重复的项目标识,但要保留它们的累计价格“累计费用”。
我最初的尝试是在最后按项目\u id分组:
select *
, sum(price) over(partition by item_id) as cum_fee
from test_table
group by item_id;
这似乎是先按项目\u id分组,然后运行窗口功能输出:
item_id price transaction_time cum_fee
1 5500 2020-01-01 00:11:11 5500
3 1100 2020-01-06 18:10:10 1100
4 1900 2020-01-02 12:00:11 1900
我知道有人在比较groupby和windowing函数,这可能意味着我们使用其中一个,而不是两个?是真的吗?
是的,实现我的目标的替代方法是什么?
1条答案
按热度按时间u1ehiz5o1#
你好像想要聚合。也许是这个?
窗口函数不会更改行数。那是什么
group by
做。