Top Banner
Prentice Hall © 2004 1 COS 346 COS 346 Day 13 Day 13
80

Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 1

COS 346COS 346

Day 13Day 13

Page 2: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

7-2

AgendaAgenda

• Questions?Questions?• Assignment 5 not CorrectedAssignment 5 not Corrected

– 2 MIA’s2 MIA’s

• Assignment 6 Posted Assignment 6 Posted – Due March 23 Due March 23

• Assignment 7 Posted Assignment 7 Posted – Due March 30Due March 30

• New Time line (New Time line ( • More on SQL & SQL ServerMore on SQL & SQL Server

– Chap 4&5 Chap 4&5

Page 3: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

New time lineNew time line

• MarchMarch

– 19 - SQL 4 & 519 - SQL 4 & 5

– 23 - SQL 6 & 723 - SQL 6 & 7

• Assignment 6 dueAssignment 6 due

– 26 - SQL 8 & 926 - SQL 8 & 9

– 30 - SQL 1030 - SQL 10

• Assignment 7 dueAssignment 7 due

• Progress reportProgress report

• AprilApril

– 2 Database Redesign 2 Database Redesign – 6 - 6 - Database redesign Database redesign

• Quiz 2Quiz 2

• Assignment 8 due Assignment 8 due

– 9 - Managing Multiuser databases 9 - Managing Multiuser databases

– 13 - Managing Multiuser 13 - Managing Multiuser databases databases

• Assignment 9 due Assignment 9 due

– 16 Managing Multiuser databases 16 Managing Multiuser databases

– 20 Database access standards20 Database access standards

• Progress report Progress report

– 23 - Database access standards23 - Database access standards

• Assignment 10 dueAssignment 10 due

– 2727

• Quiz 3Quiz 3

• Capstones Presentations Due Capstones Presentations Due

Page 4: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 4

Chapter 4: Adding Power to QueriesChapter 4: Adding Power to Queries

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 5: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 5

OBJECTIVESOBJECTIVES

• Use logical operators (AND, OR, NOT) to Use logical operators (AND, OR, NOT) to write complex query conditions.write complex query conditions.

• Use the IN and BETWEEN operators.Use the IN and BETWEEN operators.

• Use the LIKE operator for character Use the LIKE operator for character matching.matching.

• Use the IS NULL operator when querying Use the IS NULL operator when querying for unknown values.for unknown values.

• Use expressions in WHERE clauses.Use expressions in WHERE clauses.

Page 6: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 6

LOGICAL OPERATORSLOGICAL OPERATORS (AND, OR, AND NOT) (AND, OR, AND NOT)

• AND: Joins two or more conditions, and returns AND: Joins two or more conditions, and returns results only when results only when allall of the conditions are true. of the conditions are true.

• OR: Joins two or more conditions, and returns OR: Joins two or more conditions, and returns results when results when anyany of the conditions are true.of the conditions are true.

• NOT: Negates the expression that follows it.NOT: Negates the expression that follows it.

Page 7: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 7

AND OPERATORAND OPERATOR

SELECT emp_last_name, emp_first_name, emp_gender SELECT emp_last_name, emp_first_name, emp_gender "Gender""Gender"

FROM employeeFROM employee

WHERE emp_gender = ‘F’ AND emp_last_name >= 'E'WHERE emp_gender = ‘F’ AND emp_last_name >= 'E'

ORDER BY emp_last_name;ORDER BY emp_last_name;

emp_last_name emp_first_name Gender emp_last_name emp_first_name Gender

------------- -------------- ------ ------------- -------------- ------

Joyner Suzanne FJoyner Suzanne F

Markis Marcia FMarkis Marcia F

Prescott Sherri FPrescott Sherri F

Page 8: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 8

AND OPERATORAND OPERATOR

SELECT CAST(emp_last_name AS Char (12)) "Last Name", SELECT CAST(emp_last_name AS Char (12)) "Last Name", CAST(emp_first_name AS CHAR(2)) "First Name",CAST(emp_first_name AS CHAR(2)) "First Name", CAST(emp_date_of_birth AS CHAR(12))"Birth Day",CAST(emp_date_of_birth AS CHAR(12))"Birth Day", emp_gender "Gender", ‘$’ +emp_gender "Gender", ‘$’ + CONVERT (CHAR (10), emp_salary, 1) "Salary"CONVERT (CHAR (10), emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_last_name > ‘E’WHERE emp_last_name > ‘E’AND AND emp_date_of_birth > ‘20-Jun-71’emp_date_of_birth > ‘20-Jun-71’ANDAND emp_gender = ‘M’ emp_gender = ‘M’ ANDAND emp_salary > 20000emp_salary > 20000ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name Birth Day Gender Salary Last Name First Name Birth Day Gender Salary ------------ ---------- ------------ -------- ----------- ------------ ---------- ------------ -------- ----------- Joshi Di Sep 15 1972 M $ 38,000.00Joshi Di Sep 15 1972 M $ 38,000.00Zhu Wa Dec 8 1975 M $ 43,000.00Zhu Wa Dec 8 1975 M $ 43,000.00

Page 9: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 9

OR OPERATOROR OPERATOR

SELECT emp_last_name, emp_first_name, emp_gender SELECT emp_last_name, emp_first_name, emp_gender

FROM employeeFROM employee

WHERE emp_gender = 'F' OR emp_last_name >= 'M'WHERE emp_gender = 'F' OR emp_last_name >= 'M'

ORDER BY emp_last_name;ORDER BY emp_last_name;

emp_last_name emp_first_name emp_gender emp_last_name emp_first_name emp_gender

------------- -------------- ---------- ------------- -------------- ----------

Joyner Suzanne FJoyner Suzanne F

Markis Marcia FMarkis Marcia F

Prescott Sherri FPrescott Sherri F

Zhu Waiman MZhu Waiman M

Page 10: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 10

NOT OPERATORNOT OPERATOR

SELECT emp_last_name, emp_first_name, SELECT emp_last_name, emp_first_name, emp_dpt_numberemp_dpt_number

FROM employeeFROM employee

WHERE NOT emp_dpt_number = 7WHERE NOT emp_dpt_number = 7

ORDER BY emp_last_name;ORDER BY emp_last_name;  

emp_last_name emp_first_name emp_dpt_number emp_last_name emp_first_name emp_dpt_number

------------- -------------- -------------- ------------- -------------- --------------

Amin Hyder 3Amin Hyder 3

Bordoloi Bijoy 1Bordoloi Bijoy 1

Joyner Suzanne 3Joyner Suzanne 3

Markis Marcia 3Markis Marcia 3

Page 11: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 11

Combining OR and AND OperatorsCombining OR and AND Operators

• When the AND operator is combined with When the AND operator is combined with OR, the SQL Server will evaluate the OR, the SQL Server will evaluate the condition connected by the AND condition connected by the AND firstfirst before any conditions connected with OR.before any conditions connected with OR.

• Parentheses must be used to force an order Parentheses must be used to force an order of operation. of operation.

Page 12: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 12

Combining OR and AND Operators Contd.Combining OR and AND Operators Contd.

Q? Q?

Display a list of employees with a last Display a list of employees with a last name that begins with or is greater than the name that begins with or is greater than the letter ‘E’, and who are either female or works letter ‘E’, and who are either female or works in department number #1.in department number #1.

Page 13: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 13

Combining OR and AND Operators Contd.Combining OR and AND Operators Contd.

SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", CAST(emp_first_name AS CHAR(12)) "First Name", CAST(emp_first_name AS CHAR(12)) "First Name", emp_gender, emp_dpt_number emp_gender, emp_dpt_number FROM employeeFROM employeeWHERE emp_last_name >= ‘E’ AND emp_gender = ‘F’ OR WHERE emp_last_name >= ‘E’ AND emp_gender = ‘F’ OR

emp_dpt_number = 1emp_dpt_number = 1ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name emp_gender emp_dpt_number Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- ------------ ------------ ---------- -------------- Bordoloi Bijoy M 1Bordoloi Bijoy M 1Joyner Suzanne F 3Joyner Suzanne F 3Markis Marcia F 3Markis Marcia F 3Prescott Sherri F 7Prescott Sherri F 7

Is this answer correct?Is this answer correct?

Page 14: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 14

Combining OR and AND Operators Combining OR and AND Operators SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", CAST(emp_first_name AS CHAR(12)) "First Name", CAST(emp_first_name AS CHAR(12)) "First Name", emp_gender, emp_dpt_number emp_gender, emp_dpt_number FROM employeeFROM employeeWHERE emp_last_name >= ‘E’ AND WHERE emp_last_name >= ‘E’ AND (emp_gender = ‘F’ OR emp_dpt_number = 1)(emp_gender = ‘F’ OR emp_dpt_number = 1)ORDER BY emp_last_name; ORDER BY emp_last_name;

Last Name First Name emp_gender emp_dpt_number Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- ------------ ------------ ---------- -------------- Joyner Suzanne F 3Joyner Suzanne F 3Markis Marcia F 3Markis Marcia F 3Prescott Sherri F 7Prescott Sherri F 7  

Page 15: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 15

LISTS (IN AND NOT IN)LISTS (IN AND NOT IN)

• There are two operators that are designed for There are two operators that are designed for testing to determine if data stored in a table testing to determine if data stored in a table column is either in or not in a list or set of values.column is either in or not in a list or set of values.

• These are the IN and NOT IN operators. These are the IN and NOT IN operators. • These operators greatly simplify the task of writing These operators greatly simplify the task of writing

queries that might otherwise require a large queries that might otherwise require a large number of either OR logical operators or an number of either OR logical operators or an unwieldy use of the NOT logical operator. unwieldy use of the NOT logical operator.

Page 16: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 16

Using IN OperatorUsing IN OperatorSELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name",

CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name",

CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"

FROM employeeFROM employee

WHERE emp_salary = 43000 WHERE emp_salary = 43000 OROR emp_salary = 30000 emp_salary = 30000 OR OR emp_salary = 25000emp_salary = 25000

ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary

--------------- --------------- ------------ --------------- --------------- ------------

Amin Hyder 25000.00Amin Hyder 25000.00

Markis Marcia 25000.00Markis Marcia 25000.00

Prescott Sherri 25000.00Prescott Sherri 25000.00

Bock Douglas 30000.00Bock Douglas 30000.00

Zhu Waiman 43000.00Zhu Waiman 43000.00

Joyner Suzanne 43000.00Joyner Suzanne 43000.00

Page 17: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 17

Using IN Operator Contd.Using IN Operator Contd.SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"FROM employeeFROM employeeWHERE emp_salary WHERE emp_salary IN (43000, 30000, 25000)IN (43000, 30000, 25000)ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ------------ --------------- --------------- ------------ Amin Hyder 25000.00Amin Hyder 25000.00Markis Marcia 25000.00Markis Marcia 25000.00Prescott Sherri 25000.00Prescott Sherri 25000.00Bock Douglas 30000.00Bock Douglas 30000.00Zhu Waiman 43000.00Zhu Waiman 43000.00Joyner Suzanne 43000.00Joyner Suzanne 43000.00

Page 18: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 18

Using IN Operator Contd.Using IN Operator Contd.SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", emp_city "City"emp_city "City"FROM employeeFROM employeeWHERE emp_city IN (‘Marina’, ‘Edwardsville’, ‘St. Louis’)WHERE emp_city IN (‘Marina’, ‘Edwardsville’, ‘St. Louis’)ORDER BY emp_city;ORDER BY emp_city;

Last Name First Name City Last Name First Name City --------------- --------------- ------------------------- --------------- --------------- ------------------------- Bordoloi Bijoy EdwardsvilleBordoloi Bijoy EdwardsvillePrescott Sherri EdwardsvillePrescott Sherri EdwardsvilleAmin Hyder MarinaAmin Hyder MarinaJoyner Suzanne MarinaJoyner Suzanne MarinaBock Douglas St. LouisBock Douglas St. LouisZhu Waiman St. LouisZhu Waiman St. Louis

Page 19: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 19

Using the NOT IN OperatorUsing the NOT IN Operator

• NOT can precede IN to form negative.NOT can precede IN to form negative.• To get the list of employees who did not earn the To get the list of employees who did not earn the

three salary figures listed earlierthree salary figures listed earlier

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"FROM employeeFROM employeeWHERE emp_salary WHERE emp_salary NOT INNOT IN (43000, 30000, 25000) (43000, 30000, 25000)ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ------------ --------------- --------------- ------------ Joshi Dinesh 38000.00Joshi Dinesh 38000.00Bordoloi Bijoy 55000.00Bordoloi Bijoy 55000.00

Page 20: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 20

RANGES (BETWEEN AND NOT BETWEEN)RANGES (BETWEEN AND NOT BETWEEN)

• SQL provides two operators, BETWEEN and SQL provides two operators, BETWEEN and NOT BETWEEN that can simplify the range NOT BETWEEN that can simplify the range of values in a query.of values in a query.

• This eliminates the need to use a more This eliminates the need to use a more complex WHERE clause involving the use of complex WHERE clause involving the use of the AND logical operator.the AND logical operator.

Page 21: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 21

Using the BETWEEN OperatorUsing the BETWEEN Operator

• The following query uses the AND logical operator.The following query uses the AND logical operator.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name’’CAST(emp_first_name AS CHAR(15)) "First Name’’ ‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_salary >= 25000 AND emp_salary <= 40000WHERE emp_salary >= 25000 AND emp_salary <= 40000ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ----------- --------------- --------------- ----------- Amin Hyder $ 25,000.00Amin Hyder $ 25,000.00Markis Marcia $ 25,000.00Markis Marcia $ 25,000.00Prescott Sherri $ 25,000.00Prescott Sherri $ 25,000.00Bock Douglas $ 30,000.00Bock Douglas $ 30,000.00Joshi Dinesh $ 38,000.00Joshi Dinesh $ 38,000.00

Page 22: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 22

Using the BETWEEN Operator Contd.Using the BETWEEN Operator Contd.

• The query can be rewritten using the BETWEEN operator. The query can be rewritten using the BETWEEN operator.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", ‘ ‘$’+ Convert(char(10),emp_salary, 1) "Salary"$’+ Convert(char(10),emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_salary BETWEEN 25000 AND 40000WHERE emp_salary BETWEEN 25000 AND 40000ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ----------- --------------- --------------- ----------- Amin Hyder $ 25,000.00Amin Hyder $ 25,000.00Markis Marcia $ 25,000.00Markis Marcia $ 25,000.00Prescott Sherri $ 25,000.00Prescott Sherri $ 25,000.00Bock Douglas $ 30,000.00Bock Douglas $ 30,000.00Joshi Dinesh $ 38,000.00Joshi Dinesh $ 38,000.00

Page 23: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 23

Specifying More Than One Salary RangeSpecifying More Than One Salary Range

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", ‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"FROM employee FROM employee WHEREWHERE emp_salaryemp_salary BETWEEN 25000 AND 30000 BETWEEN 25000 AND 30000 OR emp_salary BETWEEN 40000 AND 43000OR emp_salary BETWEEN 40000 AND 43000ORDER BY emp_salaryORDER BY emp_salary;;

Last Name Salary Last Name Salary --------------- ----------- --------------- ----------- Amin $ 25,000.00Amin $ 25,000.00Markis $ 25,000.00Markis $ 25,000.00Prescott $ 25,000.00Prescott $ 25,000.00Bock $ 30,000.00Bock $ 30,000.00Zhu $ 43,000.00Zhu $ 43,000.00Joyner $ 43,000.00Joyner $ 43,000.00

Page 24: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 24

Using the NOT BETWEEN OperatorUsing the NOT BETWEEN Operator

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name",

‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"

FROM employee FROM employee

WHERE emp_salary NOT BETWEEN 28000 AND 50000WHERE emp_salary NOT BETWEEN 28000 AND 50000

ORDER BY emp_salary;ORDER BY emp_salary;

Last Name Salary Last Name Salary

--------------- ----------- --------------- -----------

Amin $ 25,000.00Amin $ 25,000.00

Markis $ 25,000.00Markis $ 25,000.00

Prescott $ 25,000.00Prescott $ 25,000.00

Bordoloi $ 55,000.00Bordoloi $ 55,000.00

Page 25: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 25

LIKE AND NOT LIKELIKE AND NOT LIKE

• The LIKE and NOT LIKE operators can be used to The LIKE and NOT LIKE operators can be used to search for data rows containing incomplete or partial search for data rows containing incomplete or partial character strings within a data column. character strings within a data column.

• The next query searches the employee table for The next query searches the employee table for employee names that begin with the characters ‘Bo’.employee names that begin with the characters ‘Bo’.

• The search is case-sensitive meaning that ‘Bo’ is not The search is case-sensitive meaning that ‘Bo’ is not equivalent to ‘BO’.equivalent to ‘BO’.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name"CAST(emp_first_name AS CHAR(15)) "First Name"FROM employeeFROM employeeWHERE emp_last_name LIKE 'Bo%';WHERE emp_last_name LIKE 'Bo%';

Page 26: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 26

LIKE AND NOT LIKELIKE AND NOT LIKE

Wild cardWild card MeaningMeaning

% % (percent) (percent) any string of zero or more charactersany string of zero or more characters

_ (underscore)_ (underscore) any single characterany single character

[ ] (brackets)[ ] (brackets) any single character within a specified any single character within a specified range such as ‘range such as ‘aa’ to ‘’ to ‘dd’, inclusive [a-d] ’, inclusive [a-d] or a set of characters such as or a set of characters such as [aeiouy][aeiouy]

[^] (not brackets)[^] (not brackets) any single character any single character not not in the in the specified range or set (e.g., [^a-f] )specified range or set (e.g., [^a-f] )

Page 27: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 27

MORE EXAMPLESMORE EXAMPLES

• LIKE ‘%inger’ will search for every name that ends LIKE ‘%inger’ will search for every name that ends with ‘inger’ (Rwith ‘inger’ (Ringeringer, Str, Stringeringer).).

• LIKE ‘%en%’ will search for every name that has the LIKE ‘%en%’ will search for every name that has the letters ‘en’ in the name (Bletters ‘en’ in the name (Benennet, Grenet, Greenen, McBadd, McBaddenen).).

• LIKE ‘_heryl’ will search for every six-letter name LIKE ‘_heryl’ will search for every six-letter name ending with ‘heryl’ (Cending with ‘heryl’ (Cherylheryl). Notice how this is ). Notice how this is different than ‘%heryl’ ,which would return names different than ‘%heryl’ ,which would return names that are six characters or more.that are six characters or more.

Page 28: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 28

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

• LIKE ‘[CK]ars[eo]n’ will search for every six-letter LIKE ‘[CK]ars[eo]n’ will search for every six-letter name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ or ‘o’ between ‘ars’ and ‘n’ (e.g., 'or ‘o’ between ‘ars’ and ‘n’ (e.g., 'CCarsarseen,' ‘n,' ‘KKarsarseen,’ n,’ ‘‘CCarsarsoon,’ and ‘n,’ and ‘KKarsarsoon’.n’.

• LIKE ‘[M-Z]inger’ will search for all the names ending LIKE ‘[M-Z]inger’ will search for all the names ending with ‘inger’ that begin with any single letter ‘M’ thru ‘Z’ with ‘inger’ that begin with any single letter ‘M’ thru ‘Z’ (R(Ringeringer).).

• LIKE ‘M[^c]%’ will search for all the names that begin LIKE ‘M[^c]%’ will search for all the names that begin with ‘M’ not having ‘c’ as the second letter.with ‘M’ not having ‘c’ as the second letter.

Page 29: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 29

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

•The SELECT statement shown below generates a The SELECT statement shown below generates a result table that includes all DISTINCT rows where result table that includes all DISTINCT rows where the employee social security number in the the employee social security number in the assignmentassignment table ends with the numbers 555. table ends with the numbers 555.

SELECT DISTINCT work_emp_ssn "Emp SSN"SELECT DISTINCT work_emp_ssn "Emp SSN"

FROM assignmentFROM assignment

WHERE work_emp_ssn LIKE ‘%555’WHERE work_emp_ssn LIKE ‘%555’

Emp SSN Emp SSN

--------- ---------

999555555999555555

Page 30: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 30

UNKNOWN VALUESUNKNOWN VALUES (IS NULL and IS NOT NULL) (IS NULL and IS NOT NULL)

• NULL value is NULL value is not synonymous not synonymous with “zero” with “zero” (numerical values) or “blank” (character values).(numerical values) or “blank” (character values).

• NULL values allow users to distinguish between a NULL values allow users to distinguish between a deliberate entry of zero/blank and a non entry of deliberate entry of zero/blank and a non entry of data.data.

SELECT *SELECT *

FROM assignment FROM assignment

WHERE work_hours IS NULL;WHERE work_hours IS NULL;

work_emp_ssn work_pro_number work_hours work_emp_ssn work_pro_number work_hours

------------ --------------- ---------- ------------ --------------- ----------

999444444 1 NULL999444444 1 NULL

999666666 20 NULL999666666 20 NULL

Page 31: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 31

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

SELECT *SELECT *FROM assignmentFROM assignmentWHERE work_hours = 0;WHERE work_hours = 0;

work_emp_ssn work_pro_number work_hours work_emp_ssn work_pro_number work_hours ------------ --------------- ---------- ------------ --------------- ---------- (0 row(s) affected)(0 row(s) affected)

• The query did not return a result table because none The query did not return a result table because none of the rows in the assignment table have a zero of the rows in the assignment table have a zero value for work_hours. Thus, you can see that zero value for work_hours. Thus, you can see that zero (0) is a value, not an “unknown value.”(0) is a value, not an “unknown value.”

Page 32: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 32

MORE EXAMPLESMORE EXAMPLES

• The NOT NULL condition can also be tested.The NOT NULL condition can also be tested.

SELECT *SELECT *

FROM assignment FROM assignment

WHERE work_hours IS NOT NULL;WHERE work_hours IS NOT NULL;

(15 row(s) affected)(15 row(s) affected)

• The result table contains all the rows where The result table contains all the rows where work_hours column contains a value. work_hours column contains a value.

Page 33: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 33

EXPRESSIONS IN SELECT CLAUSESEXPRESSIONS IN SELECT CLAUSES

• An expression is formed by combining a column An expression is formed by combining a column name or constant with an arithmetic operator.name or constant with an arithmetic operator.

• The arithmetic operators used in SQL are The arithmetic operators used in SQL are

SYMBOL OPERATION ORDER

* Multiplication 1

/ Division 1

% Modulo 1

+ Addition 2

- Subtraction 2

Page 34: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 34

EXAMPLEEXAMPLESELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", emp_salary/12emp_salary/12 "Monthly Salary" "Monthly Salary"FROM employeeFROM employeeWHERE emp_salary/12 > 3500WHERE emp_salary/12 > 3500ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name Monthly Salary Last Name First Name Monthly Salary --------------- --------------- --------------- --------------- --------------------- --------------------- Bordoloi Bijoy Bordoloi Bijoy 4583.33334583.3333Joyner Suzanne Joyner Suzanne 3583.33333583.3333Zhu Waiman Zhu Waiman 3583.33333583.3333

Page 35: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 35

EXPRESSIONSEXPRESSIONS

• When expression is used in select with a column When expression is used in select with a column name it has no effect on the table’s underlying name it has no effect on the table’s underlying values.values.

• The data contained in each column must be The data contained in each column must be numeric data.numeric data.

• The result of an arithmetic operation on The result of an arithmetic operation on NULL is NULL. NULL is NULL.

Page 36: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 36

Examples of Operations on NullsExamples of Operations on NullsSELECT work_emp_ssn "SSN", work_pro_number SELECT work_emp_ssn "SSN", work_pro_number

"Project","Project", work_hours/40 "Avg Hours/Week"work_hours/40 "Avg Hours/Week"FROM assignmentFROM assignmentWHERE work_pro_number = 1WHERE work_pro_number = 1ORDER BY work_emp_ssn;ORDER BY work_emp_ssn;

SSN Project Avg Hours/Week SSN Project Avg Hours/Week --------- ------- -------------- --------- ------- -------------- 999111111 1 .785000999111111 1 .785000999444444 1 NULL999444444 1 NULL999888888 1 .525000999888888 1 .525000

Page 37: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 37

Examples of Operations on Nulls Contd.Examples of Operations on Nulls Contd. Table: Contract_EmployeeTable: Contract_Employee

emp_id, emp_id, emp_jobemp_job emp_salaryemp_salary emp_bonus emp_bonus

1010 BIG BOSS BIG BOSS 100000 100000 NULLNULL

2020 LITTLE LITTLE BOSS BOSS

50000 50000 NULLNULL

3030 WARRIOR WARRIOR 10000 10000 20002000

4040 WARRIOR WARRIOR 10000 10000 30003000

Page 38: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 38

Examples of Operations on Nulls Examples of Operations on Nulls Contd.Contd.

SELECT emp_id, emp_job, emp_salary+emp_bonus SELECT emp_id, emp_job, emp_salary+emp_bonus "Total Comp""Total Comp"

FROM contract_employee; FROM contract_employee;

emp_id emp_job Total Comp emp_id emp_job Total Comp --------- --------------- --------- --------------- --------------------- --------------------- 10 BIG BOSS 10 BIG BOSS NULLNULL20 LITTLE BOSS NULL20 LITTLE BOSS NULL30 WORKER 30 WORKER 12000.000012000.000040 WORKER 40 WORKER 14000.000014000.0000

Page 39: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Pretice Hall © 2004 39

SUMMARYSUMMARY

• Logical operators (AND and OR) in the WHERE clause add Logical operators (AND and OR) in the WHERE clause add power to your queries.power to your queries.

• When the AND operator is combined with OR, AND takes When the AND operator is combined with OR, AND takes precedence over OR. Always use parentheses' to clarify the precedence over OR. Always use parentheses' to clarify the order of operation. order of operation.

• IN AND NOT IN operators are used to compare a column IN AND NOT IN operators are used to compare a column against several values.against several values.

• The BETWEEN operators specifies an The BETWEEN operators specifies an inclusiveinclusive range of range of values.values.

• Use the LIKE operator for incomplete search of character Use the LIKE operator for incomplete search of character string.string.

• Use the IS NULL operator when querying for unknown Use the IS NULL operator when querying for unknown values.values.

• The result of an arithmetic operation on NULL is NULL. The result of an arithmetic operation on NULL is NULL.

Page 40: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 40

Chapter 5: Aggregate Functions Chapter 5: Aggregate Functions and Grouping of Dataand Grouping of Data

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 41: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 41

OBJECTIVESOBJECTIVES

• Write queries with aggregate functions: SUM, Write queries with aggregate functions: SUM, AVG, COUNT, MAX, and MIN.AVG, COUNT, MAX, and MIN.

• Use the GROUP BY clause to answer complex Use the GROUP BY clause to answer complex managerial questions.managerial questions.

• Use the GROUP BY clause with the WHERE Use the GROUP BY clause with the WHERE and ORDER BY clauses.and ORDER BY clauses.

• Use the HAVING clause to filter out rows from Use the HAVING clause to filter out rows from a result table.a result table.

Page 42: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 42

AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

• Aggregate row functions give the user the Aggregate row functions give the user the ability to answer business questions such as:ability to answer business questions such as:

What is the average salary of an employee What is the average salary of an employee in the company?in the company?

What were the total salaries for a particular What were the total salaries for a particular year?year?

What are the maximum and minimum What are the maximum and minimum salaries in the Computer Department? salaries in the Computer Department?

Page 43: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 43

AGGREGATE ROW FUNCTIONS Contd. AGGREGATE ROW FUNCTIONS Contd.

• Aggregate functions perform a variety of Aggregate functions perform a variety of actions such as counting all the rows in a actions such as counting all the rows in a table, averaging a column’s data, and table, averaging a column’s data, and summing numeric data.summing numeric data.

• Aggregates can also search a table to find Aggregates can also search a table to find the highest “MAX” or lowest “MIN” the highest “MAX” or lowest “MIN” values in a column. values in a column.

Page 44: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 44

AGGREGATE ROW FUNCTIONS Contd.AGGREGATE ROW FUNCTIONS Contd.

There are two rules that you must understand and There are two rules that you must understand and follow when using aggregates: follow when using aggregates:

• Aggregate functions can be used in both the Aggregate functions can be used in both the SELECT and HAVING clauses (the HAVING SELECT and HAVING clauses (the HAVING clause is covered later in this chapter).clause is covered later in this chapter).

• Aggregate functions cannotAggregate functions cannot be used in a be used in a WHERE clause.WHERE clause.

Page 45: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 45

EXAMPLEEXAMPLE

• The following query The following query is wrong and will produce an is wrong and will produce an error message.error message.

SELECT *SELECT *FROM employeeFROM employeeWHERE emp_salary > AVG(emp_salary) ;WHERE emp_salary > AVG(emp_salary) ;

Msg 147, Level 15, State 1, Line 4Msg 147, Level 15, State 1, Line 4

An aggregate may not appear in the WHERE clause unless it is in An aggregate may not appear in the WHERE clause unless it is in subquery contained in a HAVING clause or a select list, and the subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.column being aggregated is an outer reference.

..  

Page 46: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 46

AGGREGATE ROW FUCTIONSAGGREGATE ROW FUCTIONS

• List of aggregate functions including their syntax List of aggregate functions including their syntax and use.and use.

Function Syntax Function Use

SUM( [ALL | DISTINCT] expression )

The total of the (distinct) values in a numeric column/expression.

AVG( [ALL | DISTINCT] expression )

The average of the (distinct) values in a numeric column/expression.

COUNT( [ALL | DISTINCT] expression )

The number of (distinct) non-NULL values in a column/expression.

COUNT(*) The number of selected rows.

MAX(expression) The highest value in a column/expression.

MIN(expression) The lowest value in a column/expression.

Page 47: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 47

Agg. Function Example: COUNT(*)Agg. Function Example: COUNT(*)

• If a manager needs to know how many employees If a manager needs to know how many employees work in the organization, COUNT(*) can be used to work in the organization, COUNT(*) can be used to produce this information. produce this information.

• The COUNT(*) function counts all rows in a table. The COUNT(*) function counts all rows in a table. • The wild card asterisk (*) would be used as the The wild card asterisk (*) would be used as the

parameter in the function. parameter in the function.

SELECT COUNT(*)SELECT COUNT(*)FROM employee;FROM employee;

----------- ----------- 88

Page 48: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 48

COUNT(* )COUNT(* )

• The result table for the COUNT(*) The result table for the COUNT(*) function is a single function is a single scalarscalar value. value.

• Notice that the result table has no Notice that the result table has no column heading. column heading.

• The output column can be assigned a The output column can be assigned a more meaningful column name as is more meaningful column name as is shown in the revised query.shown in the revised query.

Page 49: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 49

COUNT(*) Contd.COUNT(*) Contd.

• This is accomplished by simply listing the desired This is accomplished by simply listing the desired column name inside double quotes after the column name inside double quotes after the aggregate function specification.aggregate function specification.

SELECT COUNT(*) "Number of SELECT COUNT(*) "Number of Employees"Employees"

FROM employee;FROM employee;

Number of EmployeesNumber of Employees

------------------------------------------------------

88

Page 50: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 50

COUNT(*) Contd.COUNT(*) Contd.

• COUNT(*) is used to count all the rows in a table.COUNT(*) is used to count all the rows in a table.• COUNT(column name) does almost the same thing. COUNT(column name) does almost the same thing.

The difference is that you may define a specific The difference is that you may define a specific column to be counted.column to be counted.

• When column name is specified in the COUNT When column name is specified in the COUNT function, rows containing a NULL value in the function, rows containing a NULL value in the specified column are omitted. specified column are omitted.

• A NULL value stands for “unknown” or A NULL value stands for “unknown” or “unknowable” and must not be confused with a blank “unknowable” and must not be confused with a blank or zero. or zero.

Page 51: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 51

COUNT (*) Contd.COUNT (*) Contd.SELECT COUNT(emp_superssn) "Number of Supervised SELECT COUNT(emp_superssn) "Number of Supervised Employees"Employees"FROM employee;FROM employee;

Number of Supervised EmployeesNumber of Supervised Employees------------------------------------------------------

77

In contrast the count(*) will count each row regardless of NULL In contrast the count(*) will count each row regardless of NULL values.values.

SELECT COUNT(*) SELECT COUNT(*) ““Number of EmployeesNumber of Employees””FROM employee;FROM employee;Number of EmployeesNumber of Employees--------------------------------------

88

Page 52: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 52

Using the AVG FunctionUsing the AVG Function

• AVG function is used to compute the average value AVG function is used to compute the average value for the for the emp_salaryemp_salary column in the column in the employeeemployee table. table.

• For example, the following query returns the For example, the following query returns the average of the employee salaries. average of the employee salaries.

SELECT ‘$’+ CONVERT(Char(10), AVG(emp_salary), 1) SELECT ‘$’+ CONVERT(Char(10), AVG(emp_salary), 1) "Average Employee Salary""Average Employee Salary"

FROM employee;FROM employee;

Average Employee Salary Average Employee Salary

----------------------- -----------------------

$ 35,500.00$ 35,500.00

Page 53: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 53

More ExamplesMore Examples

• What is the average salary What is the average salary offeredoffered to employees? to employees?

• This question asks you to incorporate the concept of This question asks you to incorporate the concept of computing the average of the distinct salaries paid by the computing the average of the distinct salaries paid by the organization.organization.

• The same query with the DISTINCT keyword in the The same query with the DISTINCT keyword in the aggregate function returns a different average.aggregate function returns a different average.

SELECT ‘$’+ CONVERT(Char(10), AVG(DISTINCT emp_salary), 1) SELECT ‘$’+ CONVERT(Char(10), AVG(DISTINCT emp_salary), 1) "Average Employee Salary""Average Employee Salary"

FROM employee;FROM employee;

Average Employee SalaryAverage Employee Salary

----------------------------------------------

$ 38,200.00$ 38,200.00

Page 54: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 54

Using the SUM FunctionUsing the SUM Function

• The SUM function can compute the total of a The SUM function can compute the total of a specified table column.specified table column.

• The SELECT statement shown here will return the The SELECT statement shown here will return the total of the total of the emp_salaryemp_salary column from the column from the employeeemployee table. table.

SELECT ‘$’+ CONVERT(Char(10), SUM(emp_salary), 1) "Total Salary"SELECT ‘$’+ CONVERT(Char(10), SUM(emp_salary), 1) "Total Salary"

FROM employee;FROM employee;

Total SalaryTotal Salary

------------------------

$ 284,000.00$ 284,000.00

Page 55: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 55

More ExamplesMore Examples

• If management is preparing a budget for various If management is preparing a budget for various departments, you may be asked to write a query to departments, you may be asked to write a query to compute the total salary for different departments. compute the total salary for different departments.

• The query shown here will compute the total The query shown here will compute the total emp_salary for employees assigned to department emp_salary for employees assigned to department #7.#7.

SELECT SUM(emp_salary) "Total Salary Dept 7"SELECT SUM(emp_salary) "Total Salary Dept 7"FROM employeeFROM employeeWHERE emp_dpt_number = 7;WHERE emp_dpt_number = 7;

  Total Salary Dept 7Total Salary Dept 7--------------------------------------

136000.0000136000.0000

Page 56: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 56

MIN and MAX FunctionsMIN and MAX Functions

• The MIN function returns the lowest value stored in a data The MIN function returns the lowest value stored in a data column.column.

• The MAX function returns the largest value stored in a data The MAX function returns the largest value stored in a data column. column.

• Unlike SUM and AVG, the MIN and MAX functions work Unlike SUM and AVG, the MIN and MAX functions work with both numeric and with both numeric and charactercharacter data columns. data columns.

SELECT MIN(emp_last_name), MAX(emp_last_name)SELECT MIN(emp_last_name), MAX(emp_last_name)

FROM employee;FROM employee;

------------------------- -------------------------------------------------- -------------------------

Amin ZhuAmin Zhu

Page 57: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 57

Using GROUP BY with Aggregate Using GROUP BY with Aggregate FunctionsFunctions

• The power of aggregate functions is greater when The power of aggregate functions is greater when combined with the GROUP BY clause. combined with the GROUP BY clause.

• In fact, the GROUP BY clause is rarely used without In fact, the GROUP BY clause is rarely used without an aggregate function. an aggregate function.

• It is possible to use the GROUP BY clause without It is possible to use the GROUP BY clause without aggregates, but such a construction has very limited aggregates, but such a construction has very limited functionality, and could lead to a result table that is functionality, and could lead to a result table that is confusing or misleading. confusing or misleading.

Page 58: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 58

Using GROUP BY with Aggregate Using GROUP BY with Aggregate Functions Contd.Functions Contd.

When properly used, the GROUP BY clause enables When properly used, the GROUP BY clause enables you to use aggregate functions to answer more you to use aggregate functions to answer more complex managerial questions such as: complex managerial questions such as:

» What is the average salary of employees in each What is the average salary of employees in each department?department?

» How many employees work in each department?How many employees work in each department?» How many employees are working on a particular How many employees are working on a particular

project?project?

Page 59: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 59

ExampleExample

• The following query displays how many employees The following query displays how many employees work for each department?work for each department?

SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY emp_dpt_number;GROUP BY emp_dpt_number;

Department Employee CountDepartment Employee Count

---------- ------------------------ --------------

1 11 1

3 33 3

7 47 4  

Page 60: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 60

GROUP BY ClauseGROUP BY Clause

• SQL Server provides some flexibility in SQL Server provides some flexibility in specifying the GROUP BY clause.specifying the GROUP BY clause.

• For example, the column name used in a For example, the column name used in a GROUP BY does not have to be listed in the GROUP BY does not have to be listed in the SELECT clause; however, it must be a SELECT clause; however, it must be a column name from one of the tables listed in column name from one of the tables listed in the FROM clause. the FROM clause.

Page 61: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 61

ExampleExample

• We could rewrite the last query without specifying We could rewrite the last query without specifying the the emp_dpt_numberemp_dpt_number column as part of the result column as part of the result table, but as you can see below, the results are rather table, but as you can see below, the results are rather cryptic without the cryptic without the emp_dpt_numberemp_dpt_number column to column to identify the meaning of the aggregate count. identify the meaning of the aggregate count.

SELECT COUNT(*) "Employee Count"SELECT COUNT(*) "Employee Count"FROM employeeFROM employeeGROUP BY emp_dpt_number;GROUP BY emp_dpt_number;

Employee CountEmployee Count----------------------------113344  

Page 62: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 62

GROUP BY ClauseGROUP BY Clause

• Note, however, that if your SELECT clause Note, however, that if your SELECT clause includes includes bothboth column names and aggregate column names and aggregate functions, then you functions, then you mustmust also have a GROUP also have a GROUP BY clause in your query. Additionally, the BY clause in your query. Additionally, the column name(s) in the GROUP BY clause column name(s) in the GROUP BY clause must includemust include the column name(s) listed in the the column name(s) listed in the SELECT clause. Otherwise, SQL Server will SELECT clause. Otherwise, SQL Server will return error messages. return error messages.

Page 63: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 63

GROUP BY Clause Contd.GROUP BY Clause Contd.

SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"

FROM employee; FROM employee;

Server: Msg 8118, Level 16, State 1, Line 2Server: Msg 8118, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid in the select Column 'employee.emp_dpt_number' is invalid in the select list because it is not contained in an aggregate list because it is not contained in an aggregate function and there is no GROUP BY clausefunction and there is no GROUP BY clause

SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY emp_city;GROUP BY emp_city;

Server: Msg 8120, Level 16, State 1, Line 2Server: Msg 8120, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid in the select Column 'employee.emp_dpt_number' is invalid in the select list because it is not contained in an aggregate list because it is not contained in an aggregate function and there is no GROUP BY clause.function and there is no GROUP BY clause.

Page 64: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 64

GROUP BY Clause Contd.GROUP BY Clause Contd.

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", COUNT(*) "Department", COUNT(*) "Employee Count""Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_numberemp_dpt_number;;

Department Employee CountDepartment Employee Count

---------- ------------------------ --------------

1 11 1

3 33 3

7 47 4  

Page 65: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 65

Using GROUP BY with ExpressionsUsing GROUP BY with Expressions

• In addition to column names, any expression listed in a In addition to column names, any expression listed in a SELECT clause can be used with a GROUP BY clause.SELECT clause can be used with a GROUP BY clause.

SELECT CAST(AVG(emp_salary)AS Decimal(10,2)) "Current Average Salary", SELECT CAST(AVG(emp_salary)AS Decimal(10,2)) "Current Average Salary", CAST(AVG(CAST(AVG(emp_salary* 1.25emp_salary* 1.25)AS Decimal(10,2)) "New Average Salary")AS Decimal(10,2)) "New Average Salary"FROM employeeFROM employeeGROUP BY GROUP BY emp_salary * 1.25emp_salary * 1.25;;

Current Average Salary New Average Salary Current Average Salary New Average Salary ---------------------- ------------------ ---------------------- ------------------ 25000.00 31250.0025000.00 31250.0030000.00 37500.0030000.00 37500.0038000.00 47500.0038000.00 47500.0043000.00 53750.0043000.00 53750.0055000.00 68750.0055000.00 68750.00

Page 66: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 66

Using GROUP BY With a WHERE ClauseUsing GROUP BY With a WHERE Clause• The WHERE clause works to eliminate data table rows from The WHERE clause works to eliminate data table rows from

consideration consideration before before any grouping takes place. any grouping takes place.

• The query shown here produces an average hours worked result table The query shown here produces an average hours worked result table for employees with a social security number that is larger than 999-66-for employees with a social security number that is larger than 999-66-0000. 0000.

SELECT work_emp_ssn SSN, AVG(work_hours) "Average Hours Worked"SELECT work_emp_ssn SSN, AVG(work_hours) "Average Hours Worked"

FROM assignment FROM assignment

WHERE work_emp_ssn > 999660000WHERE work_emp_ssn > 999660000

GROUP BY work_emp_ssn;GROUP BY work_emp_ssn;

SSN Average Hours Worked SSN Average Hours Worked

--------- ----------------------------- --------------------

999666666 NULL999666666 NULL

999887777 20.500000999887777 20.500000

999888888 21.500000999888888 21.500000

Page 67: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 67

Using GROUP BY With an ORDER BY ClauseUsing GROUP BY With an ORDER BY Clause

• The ORDER BY clause allows you to specify The ORDER BY clause allows you to specify how rows in a result table are sorted. how rows in a result table are sorted.

• The default ordering is from smallest to largest The default ordering is from smallest to largest value. value.

• A GROUP BY clause in a SELECT statement A GROUP BY clause in a SELECT statement will determine the sort order of rows in a result will determine the sort order of rows in a result table.table.

• The sort order can be changed by specifying an The sort order can be changed by specifying an ORDER BY clause after the GROUP BY ORDER BY clause after the GROUP BY clause. clause.

Page 68: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 68

Using GROUP BY With an ORDER BY Clause Using GROUP BY With an ORDER BY Clause Contd.Contd.

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department",

‘‘$’ + CONVERT(Char(10),AVG(emp_salary), 1) $’ + CONVERT(Char(10),AVG(emp_salary), 1) "Average Salary""Average Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

ORDER BY AVG(emp_salary);ORDER BY AVG(emp_salary);

Department Average Salary Department Average Salary

---------- -------------- ---------- --------------

3 $ 31,000.003 $ 31,000.00

7 $ 34,000.007 $ 34,000.00

1 $ 55,000.001 $ 55,000.00

Page 69: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 69

GROUP BY With a HAVING ClauseGROUP BY With a HAVING Clause

• The HAVING clause is used for aggregate The HAVING clause is used for aggregate functions in the same way that a WHERE functions in the same way that a WHERE clause is used for column names and clause is used for column names and expressions. expressions.

• The HAVING and WHERE clauses do the The HAVING and WHERE clauses do the same thing, that is filter rows from inclusion in same thing, that is filter rows from inclusion in a result table based on a condition.a result table based on a condition.

• A WHERE clause is used to filter rows A WHERE clause is used to filter rows BEFOREBEFORE the GROUPING action. the GROUPING action.

• A HAVING clause filters rows A HAVING clause filters rows AFTER AFTER the the GROUPING action. GROUPING action.

Page 70: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 70

GROUP BY With a HAVING Clause Contd.GROUP BY With a HAVING Clause Contd.

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department",

‘‘$’ + CONVERT(Char(10),AVG(emp_salary), 1) $’ + CONVERT(Char(10),AVG(emp_salary), 1) "Average Salary""Average Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

HAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

Department Average Salary Department Average Salary

---------- -------------- ---------- --------------

1 $ 55,000.001 $ 55,000.00

7 $ 34,000.007 $ 34,000.00

Page 71: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 71

GROUP BY With a HAVING Clause Contd.GROUP BY With a HAVING Clause Contd.

Conceptually, SQL performs the following steps in the Conceptually, SQL performs the following steps in the query given above.query given above.

1.   The WHERE clause filters rows that do not meet the 1.   The WHERE clause filters rows that do not meet the conditionconditionemp_dpt_number <>emp_dpt_number <> 1. 1.2.   The GROUP BY clause collects the surviving rows 2.   The GROUP BY clause collects the surviving rows into one or more groups for each unique into one or more groups for each unique emp_dpt_numberemp_dpt_number..3.   The aggregate function calculates the average salary 3.   The aggregate function calculates the average salary for each for each emp_dpt_numberemp_dpt_number grouping. grouping.4. The HAVING clause filters out the rows from the 4. The HAVING clause filters out the rows from the result table that do not meet the condition average salary result table that do not meet the condition average salary greater than $33,000.greater than $33,000.

Page 72: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 72

Combining HAVING Clause with Where clauseCombining HAVING Clause with Where clause

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", ‘‘$’ + CONVERT(Char(10),AVG(emp_salary), $’ + CONVERT(Char(10),AVG(emp_salary),

1) "Average Salary"1) "Average Salary"FROM employeeFROM employeeWHERE emp_dpt_number <> 1WHERE emp_dpt_number <> 1GROUP BY emp_dpt_numberGROUP BY emp_dpt_numberHAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

Department Average Salary Department Average Salary ---------- -------------- ---------- -------------- 7 $ 34,000.007 $ 34,000.00

Page 73: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 73

GROUP BY and HAVING ClausesGROUP BY and HAVING Clauses

Standard SQL RulesStandard SQL Rules

The most common use of a HAVING clause is to create result tables The most common use of a HAVING clause is to create result tables containing one row per group, with one or more summary values in containing one row per group, with one or more summary values in the row. To do this your query must meet the following conditions:the row. To do this your query must meet the following conditions:If a SELECT clause includes column names and aggregate functions, If a SELECT clause includes column names and aggregate functions, then columns listed in a SELECT clause must also be listed in the then columns listed in a SELECT clause must also be listed in the GROUP BY expression or they must be arguments of aggregate GROUP BY expression or they must be arguments of aggregate functions. functions.

• A GROUP BY expression can only contain column names that are in A GROUP BY expression can only contain column names that are in the SELECT clause listing.the SELECT clause listing.

• YOU cannot have a HAVING clause in the absence of the GROUP YOU cannot have a HAVING clause in the absence of the GROUP BY clause.BY clause.

Page 74: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 74

ExampleExample

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", "Department", emp_gender,emp_gender, COUNT(*) "Employee Count"COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_numberemp_dpt_number

HAVING COUNT(*) >= 2;HAVING COUNT(*) >= 2;

Server: Msg 8120, Level 16, State 1, Line 2Server: Msg 8120, Level 16, State 1, Line 2

Column 'employee.emp_gender' is invalid in the Column 'employee.emp_gender' is invalid in the select list because it is not contained in select list because it is not contained in either an aggregate function or the GROUP BY either an aggregate function or the GROUP BY

clause.clause.  

Page 75: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 75

Example Contd.Example Contd.

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", "Department", emp_gender,emp_gender,

COUNT(*) "Employee Count"COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_number, emp_genderemp_dpt_number, emp_gender

HAVING COUNT(*) >= 2;HAVING COUNT(*) >= 2;

Department emp_gender Employee Count Department emp_gender Employee Count

---------- ---------- -------------- ---------- ---------- --------------

3 F 23 F 2

7 M 37 M 3

Page 76: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 76

More ExamplesMore Examples

SELECT emp_dpt_number "Department",SELECT emp_dpt_number "Department",

COUNT(*) "Department Count",COUNT(*) "Department Count",

MAX(emp_salary) "Top Salary",MAX(emp_salary) "Top Salary",

MIN(emp_salary) "Low Salary"MIN(emp_salary) "Low Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

HAVING COUNT(*) >= 3;HAVING COUNT(*) >= 3;

Department Department Count Top Salary Low SalaryDepartment Department Count Top Salary Low Salary

---------- ---------------- ---------- -------------------- ---------------- ---------- ----------

3 3 $ 43,000 $ 25,0003 3 $ 43,000 $ 25,000

7 4 $ 43,000 $ 25,0007 4 $ 43,000 $ 25,000

Page 77: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 77

HAVING Without a GROUP BY ClauseHAVING Without a GROUP BY Clause

SELECT emp_dpt_number, AVG(emp_salary)SELECT emp_dpt_number, AVG(emp_salary)

FROM employeeFROM employee

HAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

Server: Msg 8118, Level 16, State 1, Line 2Server: Msg 8118, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid Column 'employee.emp_dpt_number' is invalid in the select list because it is not in the select list because it is not contained in an aggregate function and there contained in an aggregate function and there is no GROUP BY clause.is no GROUP BY clause.

Page 78: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 78

SQL extensions to GROUP BY and HAVING SQL extensions to GROUP BY and HAVING ClausesClauses

Examples:Examples:

• The GROUP BY ALL clause displays all groups, even those The GROUP BY ALL clause displays all groups, even those excluded from calculations by a WHERE clause.excluded from calculations by a WHERE clause.

• The GROUP BY clause can include column names or The GROUP BY clause can include column names or expressions that are not included in the SELECT clause expressions that are not included in the SELECT clause listing. listing.

• The HAVING clause can include columns or expressions that The HAVING clause can include columns or expressions that are not listed in the SELECT clause or in a GROUP BY are not listed in the SELECT clause or in a GROUP BY clause.clause.

Page 79: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 79

SQL extensions to GROUP BY and HAVING SQL extensions to GROUP BY and HAVING Clauses Contd.Clauses Contd.

Example:Example:

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", COUNT(*) "Department", COUNT(*) "Employee Count""Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_number, emp_genderemp_dpt_number, emp_gender

HAVING COUNT(*)>= 2;HAVING COUNT(*)>= 2;

Department Employee Count Department Employee Count

---------- -------------- ---------- --------------

3 23 2

7 37 3

Page 80: Prentice Hall © 20041 COS 346 Day 13. 7-2 Agenda Questions?Questions? Assignment 5 not CorrectedAssignment 5 not Corrected –2 MIA’s Assignment 6 PostedAssignment.

Prentice Hall © 2004 80

SUMMARYSUMMARYGROUPING AND SUMMARIZING

To Get This Effect: Do This:

Exclude rows before grouping: Use a WHERE clause.

Divide a result table into groups: Use a GROUP BY clause.

Calculate summary values for each group:

Include one or more aggregates in the SELECT clause listing.

Exclude groups from the result table:

Use a HAVING clause.

If This Happens: Look For This:

All qualified rows in all qualified groups display:

The SELECT clause listing contains a column name that is not in the GROUP BY clause.

All excluded groups display Query includes GROUP BY ALL