In this session, you will learn to:

Slides:



Advertisements
Similar presentations
Chapter 11 Group Functions
Advertisements

Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Databases Lab 5 Further Select Statements. Functions in SQL There are many types of functions provided. The ones that are used most are: –Date and Time.
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Enhancements to the GROUP BY Clause Fresher Learning Program January, 2012.
Database Programming Sections 5– GROUP BY, HAVING clauses, Rollup & Cube Operations, Grouping Set, Set Operations 11/2/10.
Introduction to SQL J.-S. Chou Assistant Professor.
Rationale Aspiring Database Developers should be able to efficiently query and maintain databases. This module will help students learn the Structured.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
SQL/lesson 2/Slide 1 of 45 Retrieving Result Sets Objectives In this lesson, you will learn to: * Use wildcards * Use the IS NULL and IS NOT NULL keywords.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
Introduction to Functions – Single Row Functions.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
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.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Restricting and Sorting Data
Retrieving Data Using the SQL SELECT Statement
SQL Query Getting to the data ……..
Structured Query Language
Relational Database Design
Writing Basic SQL SELECT Statements
Aggregating Data Using Group Functions
Basic select statement
Group Functions Lab 6.
Chapter 5: Aggregate Functions and Grouping of Data
Using the Set Operators
Writing Basic SQL SELECT Statements
(SQL) Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL – Entire Select.
Chapter 4 Summary Query.
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Writing Basic SQL SELECT Statements
Creating Noninput Items
CS122 Using Relational Databases and SQL
Reporting Aggregated Data Using the Group Functions
Contents Preface I Introduction Lesson Objectives I-2
Query Functions.
Section 4 - Sorting/Functions
Reporting Aggregated Data Using the Group Functions
Using the Set Operators
Reporting Aggregated Data Using the Group Functions
Objectives In this lesson, you will learn to:
Database Management System
分组函数 Schedule: Timing Topic 35 minutes Lecture 40 minutes Practice
Restricting and Sorting Data
Aggregating Data Using Group Functions
Introduction to SQL Server and the Structure Query Language
Grouping and Aggregating Data
Presentation transcript:

In this session, you will learn to: Objectives In this session, you will learn to: Use functions to customize the result set Summarize and group data Begin by sharing the objectives of the session with the students. In this session, you will explain to the students to use various system-defined functions provided by SQL Server 2005. In addition, you will teach them how to summarize and group data. You may begin the session by stating the need for various system-defined functions. Further you can state that SQL Server 2005 provides the database developer with various system-defined functions. These functions can be used to format the data returned by a query.

Using String Functions Can be used to manipulate string values in the result set Can only be used with char and varchar data types Syntax: SELECT function_name (parameters) Let’s see how… In this topic, you will explain the usage of various string functions, to the students. You can state that string functions are used to perform various string operations on the data returned by a query. Explain to the students that string functions can work only with char and varchar data types. Ask the students to refer to the Student Guide for various string functions. You can use the examples given in the Student Guide to clarify the concept to the students. Additional Input You can use the CONVERT function to convert an expression into another data type. The CONVERT function enables quick conversion of system and object information without writing several queries. The syntax of the CONVERT function is: CONVERT (datatype [(length)], expression [, style]) where, datatype is the system-defined data type. (User-defined data types cannot be used). length is the optional parameter of char, varchar, or binary data types. expression is any valid expression to be converted from one data type to another. style is the method of representing the date while converting the date data type into the character data type.

Using Date Functions Date functions: Let’s see how… Can be used to manipulate datetime values, perform arithmetic operations, and perform date parsing Let’s see how… In this topic, you need to explain the concept and usage of the date functions. Inform the students that many a time they need to perform a number of manipulations on the data stored in the date format within a table. In addition, explain that datepart is the parameter that describes the part of the date on which the function will be performed, such as month or year. Ask the students to refer to the Student Guide for a list of date functions and date parts. You can use the examples given in the Student Guide to clarify the concept to the students.

Using Mathematical Functions Can be used to manipulate numeric values in a result set Let’s see how… In this topic, you need to explain the concept of the mathematical functions. Ask the students to refer to Student Guide for the list of mathematical functions. You can use the examples given in the Student Guide to clarify the concept to the students.

Identify the utility of the datepart function. Just a minute Identify the utility of the datepart function. Reiterate the concepts taught earlier by asking the given question. Answer: The datepart function is used to extract different parts of a date value.

Just a minute The management of AdventureWorks wants to increase the shift time from 8 hours to 10 hours. Calculate the end time of the shifts based on their start time. Reiterate the concepts taught earlier by asking the given question. Answer: SELECT ShiftID, StartTime, 'EndTime' = dateadd(hh, 10, StartTime) FROM HumanResources.Shift

Using Ranking Functions Can be used to generate sequential numbers for each row or to give a rank based on specific criteria Supported by SQL Server are: row_number rank dense_rank Let’s see how… In this topic, you need to explain the concept of the ranking functions. Ensure that the concepts are clear to the students before presenting the demo. You can use the examples given in the Student Guide to clarify the concept to the students. Additional Input:

Using System Functions Can be used to query system tables Commonly used in SQL Server are: host_id host_name suser_id Let’s see how… Example: (displays terminal id) SELECT HOST_ID() Inform the students: CG Input Converting an expression You can use the CONVERT function to convert an expression into another data type. The CONVERT function enables quick conversion of system and object information without writing several queries. The syntax of the CONVERT function is: CONVERT (datatype [(length)], expression [, style]) where, datatype is the system-defined data type. (User-defined data types cannot be used). length is the optional parameter of char, varchar, or binary data types. expression is any valid expression to be converted from one data type to another. style is the method of representing the date when converting the date data type into the character data type Consider the following example, in which you need to retrieve the data of the VacationHours column from the Employee table, by converting the data into a character data type. SELECT VacationHours = CONVERT(char(10), VacationHours)FROM HumanResources.Employee The CONVERT function is used to change data from one type to another. This function is required when the SQL Server cannot convert the data implicitly. The style values are used with the CONVERT function to specify the date format when data is converted between character and date data type. SQL Server 2005 provides the following style values that can be used to change the date format. Without century (yy)Input/Output0 or 100mon dd yyyy hh:mm (AM or PM)1mm/dd/yy2yy.mm.dd3dd/mm/yy4dd.mm.yy5dd-mm-yy101mm/dd/yyyy102yyyy.mm.dd103dd/mm/yyyy104dd.mm.yyyy105dd-mm-yyyy StyleValues of the Date Format Compare the style values and observe that when the styles used are 1, 2, 3, 4, or 5, year is displayed in the yy format. Similarly, when the styles used are 101, 102, 103, 104, or 105, year is displayed in the yyyy format. Consider the following example, where you need to display the title and hire date from the Employee table. The hire date is converted from the date data type to the character data type and then displayed in the yy.mm.dd format. This is because the style specified in the function is 2. SELECT Title, CONVERT(char(10),HireDate,2) FROM HumanResources.EmployeeNote Like CONVERT, CAST also provides the same functionality.

Demo: Customizing the Result Set Problem Statement: The management at AdventureWorks, Inc. wants to view a report that displays the employee ID, designation, and age of the employees who are working as a marketing manager or a marketing specialist. The data should be displayed in uppercase. The employee details are stored in the Employee table in the AdventureWorks database. How will you display the required data?

Demo: Customizing the Result Set (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a query. 2. Execute the query to display data.

Summarizing Data by Using Aggregate Functions Can be used to summarize values of a column based on a set of rows Supported by SQL Server are: avg count min max sum Let’s see how… Aggregate Functions Tell the students that aggregate functions are used to count or to find out the average of a particular column. In addition also tell the students that these should only be used on numeric columns. Besides, when an aggregate function is used on a column, NULL values are not considered. Additional Inputs MAX and MIN functions cannot be used on the bit data type columns. Example: (AVG) SELECT 'Average Rate' = AVG (Rate) FROM HumanResources.EmployeePayHistory Example: (COUNT) SELECT 'Unique Rate' = COUNT (DISTINCT Rate) FROM HumanResources.EmployeePayHistory Example: (MIN) SELECT 'Minimum Rate' = MIN (Rate) FROM HumanResources.EmployeePayHistory Example: (MAX) SELECT 'Maximum Rate' = MAX (Rate) FROM HumanResources.EmployeePayHistory Example: (SUM) SELECT 'Sum' = SUM (DISTINCT Rate) FROM HumanResources.EmployeePayHistory

What would be the output of the following query? Just a minute What would be the output of the following query? SELECT 'Maximum Rate' = max (UnitPrice) FROM Sales.SalesOrderDetail Answer: The query displays the maximum unit price from the SalesOrderDetail table.

Data is grouped to generate summarized reports. Grouping Data Data is grouped to generate summarized reports. Clauses used to group data are: GROUP BY COMPUTE COMPUTE BY PIVOT

Grouping Data (Contd.) GROUP BY: Let’s see how… Summarizes the result set into groups as defined in the query by using aggregate functions Uses the HAVING clause to eliminate all those groups that do not match the condition Syntax: SELECT column_list FROM table_name WHERE condition [GROUP BY [ALL] expression [, expression] [HAVING search_condition] Let’s see how… GROUP BY Clause Tell the students that the GROUP BY clause is used to group the output of the SELECT statement in several groups. If ALL is used, then it ignores the restriction provided by the WHERE clause. Just like the WHERE clause, you can use the HAVING clause with the GROUP BY clause. Example: (GROUP BY) SELECT Title, Minimum = MIN(VacationHours), Maximum = MAX(VacationHours) FROM HumanResources.Employee WHERE VacationHours > 20 GROUP BY Title Example: (HAVING) SELECT Title, 'Average Vacation Hours' = AVG(VacationHours) FROM HumanResources.Employee WHERE VacationHours > 30 GROUP BY Title HAVING AVG(VacationHours) >55 Additional Inputs All columns mentioned in the GROUP BY clause have to be included in the SELECT list. If a WHERE clause is present, then the GROUP BY clause groups only those rows which are satisfied by the conditions used in the WHERE clause.

Grouping Data (Contd.) COMPUTE: COMPUTE BY: Can be used to generate summary rows by using aggregate functions COMPUTE BY: Can be used to calculate summary values of the result set on a group of data The column on which the data is to be grouped is mentioned after the BY keyword. COMPUTE BY clause Stress that the COMPUTE BY clause is used to generate totals and subtotals in a control break report. Additional Inputs The columns that are mentioned in the COMPUTE clause need to be part of the SELECT list. Use an ORDER BY clause with the COMPUTE BY clause so that rows are grouped together.

Grouping Data (Contd.) Let’s see how… Syntax: SELECT column_list FROM table_name ORDER BY column_name COMPUTE aggregate_function (column_name) [, aggregate_function (column_name)...] [BY column_name [, column_name]...] Let’s see how… Example SELECT Title, 'Average VacationHours' = VacationHours, 'Average SickLeaveHours' = SickLeaveHours FROM HumanResources.Employee WHERE Title IN ('Recruiter', 'Stocker') ORDER BY Title, VacationHours, SickLeaveHours COMPUTE AVG(VacationHours), AVG(SickLeaveHours) BY Title SELECT Title, 'Total VacationHours' = VacationHours, 'Total SickLeaveHours' = SickLeaveHours FROM HumanResources.Employee WHERE Title IN ('Recruiter', 'Stocker')ORDER BY Title, VacationHours, SickLeaveHours COMPUTE SUM(VacationHours), SUM(SickLeaveHours) BY Title COMPUTE SUM(VacationHours), SUM(SickLeaveHours)

Grouping Data (Contd.) PIVOT: Let’s see how… Is used to transform a set of columns into values Syntax: SELECT * FROM table_name PIVOT (aggregation_function (value_column) FOR pivot_column IN (column_list) ) table_alias Let’s see how… Example: SELECT DepartmentID, [3] AS 'Manager 1', [109] AS 'Manager 2', [148] AS 'Manager 3' FROM (SELECT a.DepartmentID, b.EmployeeID, b.ManagerID FROM HumanResources.Department AS a JOIN HumanResources.EmployeeDepartmentHistory AS c ON a.DepartmentID = c.DepartmentID JOIN HumanResources.Employee AS b ON c.EmployeeID = b.EmployeeID WHERE c.Enddate IS NULL) p PIVOT ( COUNT(EmployeeID) FOR ManagerID IN ([3],[109],[148] ) )AS PVT

Just a minute When grouping data, which of the following clauses helps eliminate the groups that do not match the condition specified? 1. NOT IN 2. HAVING 3. WHERE 4. COMPUTE Answer: 2. HAVING

Match the column A and with column B. Just a minute Match the column A and with column B. Column A Column B ALL Used by aggregate functions PIVOT Returns zero or more values IN Used for modifying comparison operator > Relational Operator Answer: Column A Column B ALL Used for modifying comparison operator PIVOT Relational Operator IN Returns zero or more values > Used by aggregate functions

Demo: Summarizing and Grouping Data Problem Statement: You are a database developer of AdventureWorks, Inc. The management wants to view the average quantity ordered for each product group. The data should be displayed in the descending order of ProductID. The sales details are stored in the SalesOrderHeader and SalesOrderDetails tables in the AdventureWorks database. How will you generate this report?

Demo: Summarizing and Grouping Data (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a query. 2. Execute the query to verify the result.

In this session, you learned that: Summary In this session, you learned that: The string functions are used to format data in the result set. The date functions are used to manipulate date values. The mathematical functions are used to perform numerical operations. The ranking functions are used to generate sequential numbers for each row or to give a rank based on specific criteria. The system functions are used to query system tables. The aggregate functions, such as avg, count, min, max, and sum are used to retrieve summarized data. The GROUP BY and PIVOT clauses are used to group the result set. The COMPUTE and COMPUTE BY clauses are used to calculate summarized values in a grouped result set. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.