Download presentation
Presentation is loading. Please wait.
1
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 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.
2
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.
3
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.
4
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.
5
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.
6
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
7
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:
8
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.
9
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?
10
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.
11
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
12
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.
13
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
14
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.
15
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.
16
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)
17
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
18
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
19
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
20
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?
21
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.
22
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.