假設我有下表:
CREATE TABLE sales(
id serial PRIMARY KEY,
sales_employee VARCHAR(50) NOT NULL,
fiscal_year INT NOT NULL,
sale DECIMAL(14,2) NOT NULL
);
INSERT INTO sales(sales_employee,fiscal_year,sale)
VALUES('Bob',2016,100),
('Bob',2017,150),
('Bob',2018,200),
('Alice',2016,150),
('Alice',2017,100),
('Alice',2018,200),
('John',2016,200),
('John',2017,150),
('John',2018,250);
如何獲得以下結果:
2016 Bob 100
2016 Alice 150
2016 John 200
2017 Bob 250
2017 Alice 250
2017 John 350
2018 Bob 450
2018 Alice 450
2018 John 600
實際樣本中的員工人數和年限要多得多。
uj5u.com熱心網友回復:
那是一個視窗sum:
select s.*, sum(sale) over(partition by sales_employee order by fiscal_year) as running_sales
from sales s
order by fiscal_year, sales_employee
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/524164.html
標籤:mysqlsql和窗函数
上一篇:計算超過3個帖子的用戶數
