我正在计算如下两行的运行次数,
CREATE TABLE sales ( EmpId INT,Yr INT,Sales DECIMAL(8,2) ) INSERT INTO sales (EmpId,Yr,Sales) VALUES (1,2005,12000),(1,2006,18000),2007,25000),2008,2009,(2,15000),6000),6000) SELECT EmpId,sales,SUM(Sales) OVER (PARTITION BY empid ORDER BY empid ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS TotalSales2 FROM sales
输出:
EmpId Yr sales TotalSales2 ----------------------------------- 1 2005 12000 12000 1 2006 18000 30000 1 2007 25000 55000 1 2008 25000 68000 1 2009 25000 75000 2 2005 15000 15000 2 2006 6000 21000 2 2007 6000 27000
但预期产出:
EmpId Yr Sales TotalSales2 ----------------------------------- 1 2005 12000 12000 1 2006 18000 30000 1 2007 25000 25000 1 2008 25000 50000 1 2009 25000 25000 2 2005 15000 15000 2 2006 6000 21000 2 2007 6000 6000
在这个查询中我做错了什么?
注意:sql Servre版本是2012.
解决方法
表达方式:
SUM(Sales) OVER (PARTITION BY empid ORDER BY empid ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
计算考虑当前行和其前面的2行的总和.所以它实际上是计算一个滚动总和,这是你真正不想要的.
我想你实际上正在寻找如下的东西:
;WITH CTE_Group AS ( SELECT EmpId,(ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) + 1 ) / 2 AS grp FROM sales ) SELECT EmpId,SUM(sales) OVER (PARTITION BY empid,grp ORDER BY yr) AS TotalSales2 FROM CTE_Group
上述查询使用CTE计算字段grp:该字段的值对于empid分区的前两个记录为1,对于接下来的两个记录为2,依此类推.
使用grp,我们可以按照OP的要求,计算2组的销售运行总计.
编辑:
为了抵消更大的一组记录,尝试使用(信用@Max Szczurek指出这一点):
(ROW_NUMBER() OVER (PARTITION BY empid ORDER BY yr) - 1 ) / n AS grp
其中n是每个组包含的记录数.