From Event to Action: Accelerate Your Decision Making with Real-Time Automation
03 qmds2005 session03
1. Querying and Managing Data Using SQL Server 2005
Objectives
In this session, you will learn to:
Use functions to customize the result set
Summarize and group data
Ver. 1.0 Session 3 Slide 1 of 22
2. Querying and Managing Data Using SQL Server 2005
Using String Functions
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…
Ver. 1.0 Session 3 Slide 2 of 22
3. Querying and Managing Data Using SQL Server 2005
Using Date Functions
Date functions:
Can be used to manipulate datetime values, perform arithmetic
operations, and perform date parsing
Let’s see how…
Ver. 1.0 Session 3 Slide 3 of 22
4. Querying and Managing Data Using SQL Server 2005
Using Mathematical Functions
Mathematical functions:
Can be used to manipulate numeric values in a result set
Let’s see how…
Ver. 1.0 Session 3 Slide 4 of 22
5. Querying and Managing Data Using SQL Server 2005
Just a minute
Identify the utility of the datepart function.
Answer:
The datepart function is used to extract different parts
of a date value.
Ver. 1.0 Session 3 Slide 5 of 22
6. Querying and Managing Data Using SQL Server 2005
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.
Answer:
SELECT ShiftID, StartTime, 'EndTime' =
dateadd(hh, 10, StartTime) FROM
HumanResources.Shift
Ver. 1.0 Session 3 Slide 6 of 22
7. Querying and Managing Data Using SQL Server 2005
Using Ranking Functions
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…
Ver. 1.0 Session 3 Slide 7 of 22
8. Querying and Managing Data Using SQL Server 2005
Using System Functions
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…
Ver. 1.0 Session 3 Slide 8 of 22
9. Querying and Managing Data Using SQL Server 2005
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?
Ver. 1.0 Session 3 Slide 9 of 22
10. Querying and Managing Data Using SQL Server 2005
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.
Ver. 1.0 Session 3 Slide 10 of 22
11. Querying and Managing Data Using SQL Server 2005
Summarizing Data by Using Aggregate Functions
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…
Ver. 1.0 Session 3 Slide 11 of 22
12. Querying and Managing Data Using SQL Server 2005
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.
Ver. 1.0 Session 3 Slide 12 of 22
13. Querying and Managing Data Using SQL Server 2005
Grouping Data
• Data is grouped to generate summarized reports.
• Clauses used to group data are:
GROUP BY
COMPUTE
COMPUTE BY
PIVOT
Ver. 1.0 Session 3 Slide 13 of 22
14. Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)
GROUP BY:
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…
Ver. 1.0 Session 3 Slide 14 of 22
15. Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)
COMPUTE:
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.
Ver. 1.0 Session 3 Slide 15 of 22
16. Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)
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…
Ver. 1.0 Session 3 Slide 16 of 22
17. Querying and Managing Data Using SQL Server 2005
Grouping Data (Contd.)
PIVOT:
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…
Ver. 1.0 Session 3 Slide 17 of 22
18. Querying and Managing Data Using SQL Server 2005
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
Ver. 1.0 Session 3 Slide 18 of 22
19. Querying and Managing Data Using SQL Server 2005
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
Ver. 1.0 Session 3 Slide 19 of 22
20. Querying and Managing Data Using SQL Server 2005
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?
Ver. 1.0 Session 3 Slide 20 of 22
21. Querying and Managing Data Using SQL Server 2005
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.
Ver. 1.0 Session 3 Slide 21 of 22
22. Querying and Managing Data Using SQL Server 2005
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.
Ver. 1.0 Session 3 Slide 22 of 22
Hinweis der Redaktion
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.
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.
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.
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.
Reiterate the concepts taught earlier by asking the given question.
Reiterate the concepts taught earlier by asking the given question.
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:
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/Output 0 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.Employee Note Like CONVERT, CAST also provides the same functionality.
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
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.
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.
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 Example 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)
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
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.