Hello. English in not my native language, so sorry. But
There is a complex resulting SQL query, which is essentially a report that calculates and aggregates values like
SELECT RowNumber, column2, column3,
CASE Calculated WHEN 0 THEN T1.[Today]
ELSE
CASE RowNumber
WHEN 7 THEN CAST(LAG([Today], 4) OVER (ORDER by RowNumber) / NULLIF(LAG([Today], 1) OVER (ORDER by RowNumber) , 0) * 100 AS DECIMAL(20,8))
... another similar WHEN rows ...
END
END AS [Today] ,
... more columns like previous ...
FROM ...main query...
There are about ten top-level columns in top, and they are almost all numeric, i.e. exceeding the length of one line should not be here.
However, for a large number of rows, the query execution fails with an error
The query processor is unable to produce a plan because a worktable is required, and its minimum row size exceeds the maximum allowable of 8060 bytes. A typical reason why a worktable is required is a GROUP BY or ORDER BY clause in the query.
According to the results of the research, it turned out that only the WHEN conditions in which the LAG and LEAD functions are present affect the size of the row. Although, according to common sense, for each single row with its own RowNumber, only one match to the WHEN condition should be selected, and the rest should be ignored. But no, somehow the length of the row grows exactly in proportion to the number of WHENs in which there are window functions, even if the RowNumber, which is the WHEN condition, does not match for these rows. And the row with the number RowNumber = 1 falls due to exceeding the length somewhere in the CASE RowNumber construct. What's even more crazy - the fall comes even faster (with fewer WHENs) if you specify a default value as the third parameter in window functions.
Question - does anyone understand how SQL works with these window functions? Why do they increase the length of the row even in those cases when they should not be executed at all (cut off by a WHEN mismatch)?