我正在尝试编写一个sql来计算以下输入中每个组的运行总数。只是想知道如何使用mysql来实现它。我知道如何在常规sql中使用分析函数而不是mysql。你能谈谈你对如何实施它的想法吗。
sql小提琴:http://sqlfiddle.com/#!9/59366d/19年
sql使用窗口函数:
SELECT e.Id,
SUM( e.Salary ) OVER( PARTITION BY e.Id ORDER BY e.Month ) AS cumm_sal
FROM Employee e
LEFT JOIN
(
SELECT Id,MAX(Month) AS maxmonth
FROM Employee
GROUP BY Id
) emax
ON e.Id = emax.Id
WHERE e.Month != emax.maxmonth
ORDER BY e.Id,e.Month DESC;
输入:
Create table Employee (Id int, Month int, Salary int);
insert into Employee (Id, Month, Salary) values ('1', '1', '20');
insert into Employee (Id, Month, Salary) values ('2', '1', '20');
insert into Employee (Id, Month, Salary) values ('1', '2', '30');
insert into Employee (Id, Month, Salary) values ('2', '2', '30');
insert into Employee (Id, Month, Salary) values ('3', '2', '40');
insert into Employee (Id, Month, Salary) values ('1', '3', '40');
insert into Employee (Id, Month, Salary) values ('3', '3', '60');
insert into Employee (Id, Month, Salary) values ('1', '4', '60');
insert into Employee (Id, Month, Salary) values ('3', '4', '70');
输出:
| Id | Month | Salary |
|----|-------|--------|
| 1 | 3 | 90 |
| 1 | 2 | 50 |
| 1 | 1 | 20 |
| 2 | 1 | 20 |
| 3 | 3 | 100 |
| 3 | 2 | 40 |
1条答案
按热度按时间monwx1rj1#
在mysql中,最有效的方法是使用变量:
也可以使用相关子查询执行此操作: