带有子句的聚合函数OVER
可以这样重写: FROM table AS x INNER JOIN (SELECT partition columns , AggregateWithoutOverClause(...) ... FROM ...) AS y ON x.PartitionColumns = y.PartitionColumns (如果分区列是强制性的- 非空)。
例子:
SET STATISTICS IO ON;
SET NOCOUNT ON;
-- OP's query
SELECT sal,sum(sal) over(PARTITION BY empno)
FROM emp;
-- Reqwriten query
SELECT a.sal, b.SumSal
FROM emp a
INNER JOIN (SELECT EMPNO, SUM(sal) AS SumSal FROM emp GROUP BY EMPNO) b ON a.EMPNO = b.EMPNO;
结果:
sal
----------- -----------
1 10
2 10
3 10
4 10
1 3
2 3
Table 'Worktable'. Scan count 3, logical reads 21, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'EMP'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
sal SumSal
----------- -----------
1 10
2 10
3 10
4 10
1 3
2 3
Table 'Worktable'. Scan count 3, logical reads 21, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'EMP'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
执行计划:
这将仅解释最后一个 join:
第一次连接的解释可以在 Per-group processing / Partitioning and the Common Subexpression Spool部分找到。