Pivoting and Grouping Sets

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Chapter 4 Joining Multiple Tables
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
1 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Group functions cannot be used in the WHERE clause: SELECT type_code FROM d_songs WHERE SUM (duration) = 100; (this will give an error)
Chapter 11 Group Functions
Multiple-Column Subqueries 12. Objectives After completing this lesson, you should be able to do the following: Write a multiple-column subquery Describe.
Introduction to SQL Session 2 Retrieving Data From Multiple Tables.
Advanced SQL SMSU Computer Services Short Course.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Chapter 9 Joining Data from Multiple Tables
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Relational Databases.  In week 1 we looked at the concept of a key, the primary key is a column/attribute that uniquely identifies the rest of the data.
1 Chapter 4: Creating Simple Queries 4.1 Introduction to the Query Task 4.2 Selecting Columns and Filtering Rows 4.3 Creating New Columns with an Expression.
Chapter 12 Subqueries and Merge Statements
6 Copyright © 2009, Oracle. All rights reserved. Using the Data Transformation Operators.
Monthly Sales Report 200X-Q1 XYZ Limited Co..
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
05 | SET Operators, Windows Functions, and Grouping Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Thinking in Sets and SQL Query Logical Processing.
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
Copyright © 2016 Pearson Education, Inc. CHAPTER 7: ADVANCED SQL (PART I) Modern Database Management 12 th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki.
Module 3: Grouping and Summarizing Data. Summarizing Data by Using Aggregate Functions Summarizing Grouped Data Ranking Grouped Data Creating Crosstab.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Using Subqueries to Solve Queries
More SQL: Complex Queries,
Multiple-Column Subqueries
In this session, you will learn to:
Relational Database Design
Writing Basic SQL SELECT Statements
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
02 | Advanced SELECT Statements
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Querying Multiple Tables
Structured Query Language – The Basics
20761A 10: Using Subqueries Module 10   Using Subqueries.
Using the Set Operators
20761A 11: Using Set Operators Module 11   Using Set Operators.
Using Window Ranking, Offset, and Aggregate Functions
Using Subqueries to Solve Queries
08 | Grouping Sets and Pivoting Data
Sorting and Filtering Data
Querying Multiple Tables
David M. Kroenke and David J
20761B 12: Using Set Operators Module 12   Using Set Operators.
20761B 12: Using Set Operators Module 12   Using Set Operators.
Using the Set Operators
Writing SELECT Queries
20761B 10: Using Subqueries Module 10   Using Subqueries.
Using Table Expressions
Using Subqueries to Solve Queries
SQL Subquery.
Contents Preface I Introduction Lesson Objectives I-2
Relational Database Design
Chapter 8 Advanced SQL.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Using Subqueries to Solve Queries
Using the Set Operators
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Grouping and Aggregating Data
Presentation transcript:

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

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.

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

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.

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 2006 2007 2008 -------------- ---- ---- ---- Beverages 1842 3996 3694 Condiments 962 2895 1441 Confections 1357 4137 2412 Dairy Products 2086 4374 2689 Grains/Cereals 549 2636 1377 Meat/Poultry 950 2189 1060 Produce 549 1583 858 Seafood 1286 3679 2716

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.

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

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 http://go.microsoft.com/fwlink/?LinkID=402786 SELECT <column list with aggregate(s)> FROM <source> GROUP BY GROUPING SETS( (<column_name>),--one or more columns () -- empty parentheses if aggregating all rows );

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 999 NULL 1 80 NULL 2 12 NULL 3 154 NULL 4 241 NULL 5 512 Beverages NULL 513 Condiments NULL 114 Confections NULL 372

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;

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;