I would like clarification (preferrably official) on whether certain behavior is by design or a longstanding bug. The MSDN documentation states that in the context of a recursive common table expression, an analytic function will "operate only on the subset of data passed to them by the current recursion level and not the entire set of data passed to the recursive part of the CTE." This restriction is logical and expected. However, to the contrary, the analytic function will receive only the current row rather than the current recursion level. To me, referring to "subset" and "current recursion level" clearly implies that the analytic function will receive all data in the current recursion level, and certainly not that it will see only the current row.
This unexpected behavior can be observed in the MSDN example query "Using analytical functions in a recursive CTE". However, the accompanying text explains the behavior in terms of restriction to the current recursion level, which is not the issue at all. That query is also unnecessarily convoluted; here is a simpler version that demonstrates the issue:
WITH r (Id, LvlIndex, Lvl) AS (
SELECT N, ROW_NUMBER() OVER (PARTITION BY 0 ORDER BY N), 0
FROM (VALUES (1), (2), (3), (4)) AS v (N)
UNION ALL
SELECT Id, ROW_NUMBER() OVER (PARTITION BY Lvl + 1 ORDER BY Id), Lvl + 1
FROM r
WHERE Lvl < 1
)
SELECT Id, LvlIndex, Lvl
FROM r
ORDER BY Lvl, Id;
The results from the base case have the expected ROW_NUMBER
results, while the recursive case rows all have 1
, despite being partitioned by a common value.
Could anyone provide or point me to a definitive answer on whether or not this behavior is as intended? Thanks!