ROWS & RANGE criterion
Lesson 12 of 13 in Coddy's SQL for advanced course.
As of now, we can't be flexible regarding choosing how many rows before or after to take into account. Now it is possible with ROWS & RANGE criteria. To use them we write:
OVER (ROWS BETWEEN --START-- AND --END--)
OVER (RANGE BETWEEN --START-- AND --END--)
And we can specify the following options:
CURRENT ROW- the current rown PRECEDING- rows before the current rown FOLLOWING- rows after the current row
The difference between ROWS & RANGE is that ROWS criterion doesn't care about the values, just the positions, whereas RANGE defines the window in terms of value ranges rather than row positions.
For RANGE we must specify ORDER BY --column_name-- because if not it would not know how to choose the window.
For example:
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWINGHere it creates a window that includes the current row, the row before it, and the row after it.
RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING ORDER BY levelsHere it creates a window that includes for each level (sorted in ascending order) the current level, one level before it, and one level after it. If the current level is 5 then it will include levels 4, 5, and 6.
Note: The use of RANGE BETWEEN might result in more rows being included in your window, because it includes all rows that share the same values as those in the range, while ROWS BETWEEN will always include the same number of rows (as long as they are available in the data set).
Also RANGE does not support date columns.
Challenge
EasyFor this challenge, we have newspapers for production. We would like to know the average newspapers that were printed two days before the current row and one day after. Also, we would like to know the difference between the maximum and minimum number of newspapers printed from the current date and all three days before it. Call these columns avg_newspapers and diff_newspapers respectively.
Try it yourself
All lessons in SQL for advanced
4Summary
Final challenge #13Window Functions part 2
RANK & DENSE_RANK functionsNTILE functionAggregation functionsROWS & RANGE criterion