Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Window Ranking, Offset, and Aggregate Functions

Similar presentations


Presentation on theme: "Using Window Ranking, Offset, and Aggregate Functions"— Presentation transcript:

1 Using Window Ranking, Offset, and Aggregate Functions
20761B 13: Using Window Ranking, Offset, and Aggregate Functions Module 13 For more information on window functions, see Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions (Microsoft Press). Using Window Ranking, Offset, and Aggregate Functions

2 Exploring Window Functions
20761B Module Overview 13: Using Window Ranking, Offset, and Aggregate Functions Exploring Window Functions This module will challenge learners who are new to T-SQL. Plan to stay at a high level in your presentation.

3 Lesson 1: Creating Windows with OVER
20761B Lesson 1: Creating Windows with OVER 13: Using Window Ranking, Offset, and Aggregate Functions Demonstration: Using OVER and Partitioning

4 SQL Windowing Windows extend T-SQL's set-based approach
13: Using Window Ranking, Offset, and Aggregate Functions Windows extend T-SQL's set-based approach Windows allow you to specify an order as part of a calculation, without regard to order of input or final output order Windows allow partitioning and framing of rows to support functions Window functions can simplify queries that need to find running totals, moving averages, or gaps in data Note: The example is provided as an all-at-once view of windowing functions in use. Don't get bogged down in its details yet. The source, as well as the view definition, is provided in the demonstration script for this lesson. Query description: This query returns a running total of quantity per product category. The running total will reset to zero at each change in category (partition) and is the sum of all previous rows in the current category (unbounded preceding) up to the current row. SELECT Category, Qty, Orderyear, SUM(Qty) OVER ( PARTITION BY category ORDER BY orderyear ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningQty FROM Sales.CategoryQtyYear;

5 Conceptual relationship between window elements:
Windowing Components 13: Using Window Ranking, Offset, and Aggregate Functions Conceptual relationship between window elements: The result set is the window of rows defined by the OVER clause. If there is no partition, then the window includes all rows. If a partition element is defined in the OVER clause, the conceptual subset of rows is called the window partition. If a frame is defined, the window is further restricted to the starting and ending boundaries defined by the frame. Result set (OVER) Window partition (PARTITION BY) Frame (ROWS BETWEEN)

6 20761B Using OVER 13: Using Window Ranking, Offset, and Aggregate Functions OVER defines a window, or set, of rows to be used by a window function, including any ordering With a specified window partition clause, the OVER clause restricts the set of rows to those with the same values in the partitioning elements By itself, OVER() is unrestricted and includes all rows Multiple OVER clauses can be used in a single query, each with its own partitioning and ordering, if needed For example: SUM(<col>) OVER () means to calculate the aggregate (SUM) using the underlying query's result set (all rows). SUM(<col>) OVER (PARTITION BY <col>) means to calculate the aggregate once for each window of rows restricted to only those rows with the same value in <col> as in the current row. OVER ( [ <PARTITION BY clause> ] [ <ORDER BY clause> ] [ <ROWS or RANGE clause> ] )

7 20761B Partitioning Windows 13: Using Window Ranking, Offset, and Aggregate Functions Partitioning limits a set to rows with the same value in the partitioning column Use PARTITION BY in the OVER() clause Without a PARTITION BY clause defined, OVER() creates a single partition of all rows Don't take the comparison too far, but PARTITION is conceptually similar to a GROUP BY, even if the mechanisms are very different. SELECT custid, ordermonth, qty, SUM(qty) OVER(PARTITION BY custid) AS totalbycust FROM Sales.CustOrders; custid ordermonth qty totalbycust :00: :00: :00: :00: :00: :00:

8 Window ordering provides a context to the frame
20761B Ordering and Framing 13: Using Window Ranking, Offset, and Aggregate Functions Window framing allows you to set start and end boundaries within a window partition UNBOUNDED means go all the way to boundary in direction specified by PRECEDING or FOLLOWING (start or end) CURRENT ROW indicates start or end at current row in partition ROWS BETWEEN allows you to define a range of rows between two points Window ordering provides a context to the frame Sorting by an attribute enables meaningful position of a boundary Without ordering, "start at first row" is not useful because a set has no order

9 Demonstration: Using OVER and Partitioning
20761B Demonstration: Using OVER and Partitioning 13: Using Window Ranking, Offset, and Aggregate Functions In this demonstration, you will see how to: Use OVER, PARTITION BY, and ORDER BY clauses Preparation Steps Start the 20761B-MIA-DC and 20761B-MIA-SQL virtual machines. Demonstration Steps Use OVER, PARTITION BY, and ORDER BY Clauses Ensure that the 20761D-MIA-DC and 20761B-MIA-SQL virtual machines are both running, and then log on to 20761B-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd. Run D:\Demofiles\Mod13\Setup.cmd as an administrator. In the User Account Control dialog box, click Yes. At the command prompt, type y, and then press Enter. Wait for the script to finish, and then press any key. Start SQL Server Management Studio and connect to the MIA-SQL database engine instance using Windows authentication. Open the Demo.ssmssln solution in the D:\Demofiles\Mod13\Demo folder. In Solution Explorer, open the 11 - Demonstration A.sql script file. Select the code under the comment Step 1, and then click Execute. Select the code under the comment Step 2, and then click Execute. Select the code under the comment Step 3, and then click Execute. Select the code under the comment Step 4, and then click Execute. Select the code under the comment Step 5, and then click Execute. Keep SQL Server Management Studio open for the next demonstration.

10 Lesson 2: Exploring Window Functions
20761B Lesson 2: Exploring Window Functions 13: Using Window Ranking, Offset, and Aggregate Functions Demonstration: Exploring Windows Functions

11 Defining Window Functions
20761B Defining Window Functions 13: Using Window Ranking, Offset, and Aggregate Functions A window function is a function applied to a window, or set, of rows Window functions include aggregate, ranking, distribution, and offset functions Window functions depend on set created by OVER() SELECT productid, productname, unitprice, RANK() OVER(ORDER BY unitprice DESC) AS pricerank FROM Production.Products ORDER BY pricerank;

12 Window Aggregate Functions
20761B Window Aggregate Functions 13: Using Window Ranking, Offset, and Aggregate Functions Similar to grouped aggregate functions SUM, MIN, MAX, and so on Applied to windows defined by OVER clause Window aggregate functions support partitioning, ordering, and framing SELECT custid, ordermonth, qty, SUM(qty) OVER(PARTITION BY custid) AS totalpercust FROM Sales.CustOrders;

13 Window Ranking Functions
20761B Window Ranking Functions 13: Using Window Ranking, Offset, and Aggregate Functions Ranking functions require a window order clause Partitioning is optional To display results in sorted order still requires ORDER BY! Remember that any ORDER BY within an OVER clause does not determine the order of the final result set. See the notes in the workbook about using an additional ORDER BY clause to set output order. Function Description RANK Returns the rank of each row within the partition of a result set. May include ties and gaps. DENSE_RANK Returns the rank of each row within the partition of a result set. May include ties. Will not include gaps. ROW_NUMBER Returns a unique sequential row number within partition based on current order. NTILE Distributes the rows in an ordered partition into a specified number of groups. Returns the number of the group to which the current row belongs.

14 Window Distribution Functions
13: Using Window Ranking, Offset, and Aggregate Functions Window distribution functions perform statistical analysis on data, and require a window order clause Rank distribution performed with PERCENT_RANK and CUME_DIST Inverse distribution performed with PERCENTILE_CONT and PERCENTILE_DISC

15 Window Offset Functions
20761B Window Offset Functions 13: Using Window Ranking, Offset, and Aggregate Functions Window offset functions allow comparisons between rows in a set without the need for a self-join Offset functions operate on a position relative to the current row, or to the start or end of the window frame Remind students that the default window framing is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Therefore, for LAST_VALUE to return something other than the current row, the framing needs to be set, such as to UNBOUND FOLLOWING, which will then include all subsequent rows in the window frame. A hidden slide with examples follows this one. Function Description LAG Returns an expression from a previous row that is a defined offset from the current row. Returns NULL if no row at specified position. LEAD Returns an expression from a later row that is a defined offset from the current row. Returns NULL if no row at specified position. FIRST_VALUE Returns the first value in the current window frame. Requires window ordering to be meaningful. LAST_VALUE Returns the last value in the current window frame. Requires window ordering to be meaningful.

16 Example: LEAD Offset Window Function
20761B Example: LEAD Offset Window Function 13: Using Window Ranking, Offset, and Aggregate Functions SELECT employee, orderyear ,totalsales AS currsales, LEAD (totalsales, 1,0) OVER (PARTITION BY employee ORDER BY orderyear) AS nextsales FROM Sales.OrdersByEmployeeYear ORDER BY employee, orderyear; This is a hidden slide to support the example provided in the workbook. employee orderyear currsales nextsales

17 Demonstration: Exploring Windows Functions
20761B Demonstration: Exploring Windows Functions 13: Using Window Ranking, Offset, and Aggregate Functions In this demonstration, you will see how to: Use window aggregate, ranking, and offset functions Preparation Steps Complete the previous demonstration in this module. Demonstration Steps Use Window Aggregate, Ranking, and Offset Functions In Solution Explorer, open the 21 - Demonstration B.sql script file. Select the code under the comment Step 1, and then click Execute. Select the code under the comment Step 2, and then click Execute. Select the code under the comment Step 3, and then click Execute. Select the code under the comment Step 4, and then click Execute. Select the code under the comment Step 5, and then click Execute. Select the code under the comment Step 6, and then click Execute. Select the code under the comment Step 7, and then click Execute. Select the code under the comment Step 8, and then click Execute. Select the code under the comment Step 9, and then click Execute. Select the code under the comment Step 10, and then click Execute. Select the code under the comment Step 11, and then click Execute. Close SQL Server Management Studio without saving any files.

18 Lab: Using Window Ranking, Offset, and Aggregate Functions
Exercise 3: Writing Queries That Use Window Aggregate Functions Important: When comparing your results with the provided sample outputs, the column ordering and total number of affected rows should always match. However, remember that the order of the rows in the output of a query without an ORDER BY clause is not guaranteed. Therefore, the order of the rows in the sample outputs may be different to yours. Also, the answer outputs include abbreviated results. Exercise 1: Writing Queries That Use Ranking Functions The sales department would like to rank orders by their values for each customer. You will provide the report by using the RANK function. You will also practice how to add a calculated column to display the row number in the SELECT clause. Exercise 2: Writing Queries That Use Offset Functions You need to provide separate reports to analyze the difference between two consecutive rows. This will enable business users to analyze growth and trends. Exercise 3: Writing Queries That Use Window Aggregate Functions To better understand the cumulative sales value of a customer through time and to provide the sales analyst with a year-to-date analysis, you will have to write different SELECT statements that use the window aggregate functions. Logon Information Virtual machine: 20761B-MIA-SQL User name: ADVENTUREWORKS\Student Password: Pa$$w0rd Estimated Time: 60 minutes

19 20761B Lab Scenario 13: Using Window Ranking, Offset, and Aggregate Functions As a business analyst for Adventure Works, you will be writing reports using corporate databases stored in SQL Server You have been provided with a set of business requirements for data and you will write T-SQL queries to retrieve the specified data from the databases. To fill these requests, you will need to calculate ranking values, as well as the difference between two consecutive rows, and running totals. You will use window functions to achieve these calculations.

20 Module Review and Takeaways
20761B Module Review and Takeaways 13: Using Window Ranking, Offset, and Aggregate Functions Review Question(s) Review Question(s) Question What results will be returned by a ROW_NUMBER function if there is no ORDER BY clause in the query? Answer An unordered set. Which ranking function would you use to return the values 1,1,3? Which would return 1,1,2? RANK, DENSE_RANK. Can a window frame extend beyond the boundaries of the window partition defined in the same OVER() clause? No.


Download ppt "Using Window Ranking, Offset, and Aggregate Functions"

Similar presentations


Ads by Google