Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pivoting and Grouping Sets

Similar presentations


Presentation on theme: "Pivoting and Grouping Sets"— Presentation transcript:

1 Pivoting and Grouping Sets
20761B 14: Pivoting and Grouping Sets Module 14 Pivoting and Grouping Sets

2 Lesson 1: Writing Queries with PIVOT and UNPIVOT
20761B Lesson 1: Writing Queries with PIVOT and UNPIVOT 14: Pivoting and Grouping Sets Demonstration: Writing Queries with PIVOT and UNPIVOT Question You have the following query: SELECT category, qty, orderyear FROM Sales.PivotedCategorySales UNPIVOT(qty FOR orderyear) AS unpvt; In this query, you have provided a name for the new column that will display the unpivoted values (“qty”). You have also provided a name for the column that will display the names of the unpivoted values (orderyear). What else must you provide for the UNPIVOT query to execute? Answer You must supply the names of the pivoted columns that will be unpivoted by the query.

3 20761B What Is Pivoting? 14: Pivoting and Grouping Sets Pivoting data is rotating data from a rows-based orientation to a columns-based orientation Distinct values from a single column are projected across as headings for other columns—may include aggregation Note that the graphic on the left is a partial result set—the sums on the right will not match. Pivoted data

4 Pivoting includes three phases:
20761B Elements of PIVOT 14: Pivoting and Grouping Sets Pivoting includes three phases: Grouping determines which element gets a row in the result set Spreading provides the distinct values to be pivoted across Aggregation performs an aggregation function (such as SUM) Note that no explicit GROUP BY clause is needed. PIVOT determines the grouping based on those columns in the input table (produced by the FROM clause) which are not used for aggregation or as spreading elements. The next slide shows an example of a PIVOT query. This example uses a view as the source of the subquery. Source code for the view definition is included in the demonstration script for this lesson: CREATE VIEW Sales.CategoryQtyYear AS SELECT c.categoryname AS Category, od.qty AS Qty, YEAR(o.orderdate) AS Orderyear FROM Production.Categories AS c INNER JOIN Production.Products AS p ON c.categoryid=p.categoryid INNER JOIN Sales.OrderDetails AS od ON p.productid=od.productid INNER JOIN Sales.Orders AS o ON od.orderid=o.orderid; GO In the above example, data is returned from the Sales.CategoryQtyYear view (which has been created for this purpose). The source subquery contains only Category, Qty and Orderyear columns. The PIVOT operator will group on Category, sum Qty and use the Orderyear values 2006, 2007 and 2008 as the new column headings. Finally, the results are ordered by Category. This text belongs in the Inotes section of the build slide, which corresponds to the “Pivoting Example” slide. The topic “Pivoting Example”, therefore, needs to be removed.

5 Elements of PIVOT SELECT Category, [2006],[2007],[2008]
20761B Elements of PIVOT 14: Pivoting and Grouping Sets SELECT Category, [2006],[2007],[2008] FROM (SELECT Category, Qty, Orderyear FROM Sales.CategoryQtyYear) AS D PIVOT(SUM(QTY) FOR orderyear IN ([2006],[2007],[2008])) AS pvt ORDER BY Category; Category Beverages Condiments Confections Dairy Products Grains/Cereals Meat/Poultry Produce Seafood

6 Writing Queries with UNPIVOT
20761B Writing Queries with UNPIVOT 14: Pivoting and Grouping Sets Unpivoting data is rotating data from a columns- based orientation to a rows-based orientation Spreads or splits values from one source row into one or more target rows Each source row becomes one or more rows in result set based on number of columns being pivoted Unpivoting includes three elements: Source columns to be unpivoted Name to be assigned to new values column Name to be assigned to names columns Note that no explicit GROUP BY clause is needed. PIVOT determines the grouping based on those columns in the input table (produced by the FROM clause) that are not used for aggregation or as spreading elements. This example uses a view as the source of the subquery. Source code for the view definition is included in the demonstration script for this lesson: CREATE VIEW Sales.CategoryQtyYear AS SELECT c.categoryname AS Category, od.qty AS Qty, YEAR(o.orderdate) AS Orderyear FROM Production.Categories AS c INNER JOIN Production.Products AS p ON c.categoryid=p.categoryid INNER JOIN Sales.OrderDetails AS od ON p.productid=od.productid INNER JOIN Sales.Orders AS o ON od.orderid=o.orderid; GO In the above example, data is returned from the Sales.CategoryQtyYear view (which has been created for this purpose). The source subquery contains only Category, Qty and Orderyear columns. The PIVOT operator will group on Category, and sum Qty, using the Orderyear values 2006, 2007 and 2008 as the new column headings. Finally, the results are ordered by Category. This text belongs in the Inotes section of the build slide corresponding to the “Pivoting Example” slide. The topic “Pivoting Example”, therefore, needs to be removed.

7 Lesson 2: Working with Grouping Sets
20761B Lesson 2: Working with Grouping Sets 14: Pivoting and Grouping Sets Demonstration: Using Grouping Sets Question You have the following query: SELECT e.Department, e.Country, COUNT(EmployeeID) AS Staff FROM HumanResources.Employees AS e You want to find out how many staff are in each country and how many staff are in each department. You also want to find out how many staff are in Sales in the US, and so on, with all departments in all countries where the company operates. Choose the most succinct grouping technique for this query: ( )Option 1: GROUPING SETS ( )Option 2: CUBE ( )Option 3: ROLLUP ( )Option 4: You cannot return the required data with GROUPING. Instead, use multiple queries and a UNION element. Answer (√) Option -2: CUBE

8 Writing Queries with Grouping Sets
20761B Writing Queries with Grouping Sets 14: Pivoting and Grouping Sets GROUPING SETS subclause builds on T-SQL GROUP BY clause Allows multiple groupings to be defined in same query Alternative to use of UNION ALL to combine multiple outputs (each with different GROUP BY) into one result set The next slide shows a GROUPING SETS example. For more information, see GROUPING SETS Equivalents in the SQL Server 2016 Technical Documentation: GROUPING SETS Equivalents SELECT <column list with aggregate(s)> FROM <source> GROUP BY GROUPING SETS( (<column_name>),--one or more columns () -- empty parentheses if aggregating all rows );

9 Writing Queries with Grouping Sets
20761B Writing Queries with Grouping Sets 14: Pivoting and Grouping Sets SELECT Category, Cust, SUM(Qty) AS TotalQty FROM Sales.CategorySales GROUP BY GROUPING SETS((Category),(Cust),()); Category Cust TotalQty NULL NULL NULL NULL NULL NULL NULL Beverages NULL Condiments NULL Confections NULL

10 20761B CUBE and ROLLUP 14: Pivoting and Grouping Sets CUBE provides shortcut for defining grouping sets given a list of columns All possible combinations of grouping sets created ROLLUP provides shortcut for defining grouping sets, creates combinations assuming input columns form a hierarchy Versions of SQL Server earlier than 2008 used nonstandard CUBE and ROLLUP options that will be deprecated. Use this new version going forward. Note: these examples are provided in the demonstration script for this lesson. This example is shown for illustration purposes to note the difference between the results of CUBE and ROLLUP. A more realistic example for a ROLLUP would be a hierarchy such as ROLLUP (category, subcategory, product). SELECT Category, Cust, SUM(Qty) AS TotalQty FROM Sales.CategorySales GROUP BY CUBE(Category,Cust) ORDER BY Category, Cust; SELECT Category, Cust, SUM(Qty) AS TotalQty FROM Sales.CategorySales GROUP BY ROLLUP(Category,Cust) ORDER BY Category, Cust;

11 20761B GROUPING_ID 14: Pivoting and Grouping Sets Multiple grouping sets present a problem in identifying the source of each row in the result set NULLs could come from the source data or could be a placeholder in the grouping set The GROUPING_ID function provides a method to mark a row with a 1 or 0 to identify which grouping set the row is a member of The example query is provided in the demonstration script for this lesson. Note: SQL Server also provides a GROUPING function (not discussed in this lesson), which only accepts one input to return a bit. SELECT GROUPING_ID(Category)AS grpCat, GROUPING_ID(Cust) AS grpCust, Category, Cust, SUM(Qty) AS TotalQty FROM Sales.CategorySales GROUP BY CUBE(Category,Cust) ORDER BY Category, Cust;


Download ppt "Pivoting and Grouping Sets"

Similar presentations


Ads by Google