在SQL中的行之间进行计算

时间:2015-03-27 18:35:37

标签: mysql sql

我得到了下表,我想从中填充另一个表 每个部门的每年预算都减去。

E.g。 2013-2014财务预算500:

Year    Department  Budget

2013    Finance      3000
2014    Finance      3500
2015    Finance      4000
2013    Marketing    4500
2014    Marketing    5000
2015    Marketing    5500
2013    Sales        3000
2014    Sales        3500
2015    Sales        4000

我不知道该怎么做。

2 个答案:

答案 0 :(得分:2)

在大多数现代SQL数据库系统中,您可以使用窗口功能。 MySQL没有窗口函数,但您可以执行自联接以将所需的值放在同一行上:

select
  current.year AS year,
  current.department AS department,
  current.budget - previous.budget AS increase
from
  budget current
  JOIN budget previous
    ON current.department = previous.department
      AND current.year = previous.year + 1

请注意,这将省略每个部门的最早年份,因为在这些情况下没有前一年。如果需要,可以采用不同的方式处理。

答案 1 :(得分:0)

您可以使用LEAD和LAG

CREATE TABLE #temp(FY int, Dept varchar(20), Budget int);
GO

INSERT INTO #temp VALUES
(2013,'Finance',3000),
(2014,'Finance',3500),
(2015,'Finance',2000),
(2013,'Marketing',1500),
(2014,'Marketing',5500),
(2015,'Marketing',1500),
(2013,'Sales',3000),
(2014,'Sales',1500),
(2015,'Sales',3500);
GO

SELECT FY, Dept, Budget,
LAG(Budget) OVER(PARTITION BY Dept ORDER BY FY)-Budget as PreviousYear,
LEAD(Budget) OVER(PARTITION BY Dept ORDER BY FY)-Budget as NextYear
FROM #temp;
GO