In a previous article I covered the usage of ROWS PRECEDING and FOLLOWING in the over clause. For this example I am going to use the same database and tables that I created in the previous example.
One of the new features available in TSQL in SQL Server 2012 is the ROWS UNBOUNDED PRECEDING and the ROWS UNBOUNDED FOLLOWING options. The UNBOUNDED option in available when using the PRECEDING and FOLLOWING options. Here’s how they work…
-- ROWS UNBOUNDED PRECEDING select Year, DepartmentID, Revenue, min(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS UNBOUNDED PRECEDING) as MinRevenueToDate from REVENUE order by departmentID, year;
In this example, the MinRevenueToDate lists the lowest revenue for this row and all earlier rows ordered by date in the current department id.
You can see that row 1 sets the MinRevenueToDate to 10030, and it doesn’t change until row 7 with a lower revenue year.
Then row 16 starts over for a new department with the lowest running revenue to date. Then row 21 resets to a lower revenue number.
Now for the example of UNBOUNDED FOLLOWING:
-- ROWS UNBOUNDED FOLLOWING select Year, DepartmentID, Revenue, min(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as MinRevenueBeyond from REVENUE order by departmentID, year;
Where you can see that the min(Revenue) is calculated over all of the rows from the current row to the end of the set partitioned by the departmentID.
The UNBOUNDED option is very useful to determine a calculation from the beginning of a set to the current row, or from the current row to the end of a set or group.
Keep in mind that this feature was introduced in SQL Server 2012, and is not available in earlier editions.