版本= 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");使用窗口函数获取我运行的每个item_id的累计价格:
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现在我想去掉重复的item_id。我添加窗口功能的原因是我想摆脱重复的item_id,但又想保持它们的累积价格"cum_fee“。
我最初的尝试是在最后按item_id分组:
select *
, sum(price) over(partition by item_id) as cum_fee
from test_table
group by item_id;这似乎是先按item_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和。窗口函数,这可能意味着我们使用其中之一,但不是两个都使用?是真的吗?
是,有什么替代方法可以实现我的目标?
发布于 2020-07-01 19:03:20
您似乎想要聚合。也许是这个?
select item_id, min(price), min(transaction_time), sum(price)
from test_table
group by item_id;窗口函数不会更改行数。这就是group by所做的。
https://stackoverflow.com/questions/62673487
复制相似问题