You are on page 1of 30

NIIT LTD

6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Reporting Aggregated Data


Using the Group Functions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n
NIIT LTD

Course Roadmap

Lesson 1: Introduction Lesson 6: Reporting Aggregated Data Using You are here!
Group Functions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Unit 1: Retrieving, Restricting, Lesson 7: Displaying Data from Multiple


and Sorting Data Tables Using Joins

Unit 2: Joins, Subqueries, and Lesson 8: Using Subqueries to Solve


Set operators Queries

Lesson 9: Using Set Operators


Unit 3: DML and DDL
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E display Sdata from multiple tables using
In Unit 2, you will learn about SQL statements to queryHand h
S condition i s
t is unknown, use group functions to
T H the
Joins. You will also learn to use subqueries when
u s e
aggregate data, and use set operators. NA t o
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 2


NIIT LTD

Objectives

After completing this lesson, you should be able to do the following:


• Identify the available group functions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• Describe the use of group functions


• Group data by using the GROUP BY clause
• Include or exclude grouped rows by using the HAVING clause

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S on obtaining summary
HElesson
In this lesson, you will further learn about functions.SThe
t h i s
focuses
information (such as averages) for groups of rows.
T H Youuswille discuss how to group rows in a table into
A
A MN se to
smaller sets and how to specify search criteria for groups of rows.

R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 3


NIIT LTD

Lesson Agenda

• Group functions:
– Types and syntax
– Use AVG, SUM, MIN, MAX, COUNT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

– Use the DISTINCT keyword within group functions


– NULL values in a group function
• Grouping rows:
– GROUP BY clause
– HAVING clause
• Nesting group functions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 4


NIIT LTD

Group Functions

Group functions operate on sets of rows to give one result per group.

EMPLOYEES
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Maximum salary in
EMPLOYEES table


s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
Esets of irowsSto give one result per group.
Unlike single-row functions, group functions operate H
on h s
H Sofurows
These sets may comprise the entire table or groups
T s e int the table.
N A to
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 5


NIIT LTD

Types of Group Functions

• AVG
• COUNT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• MAX
Group
• MIN functions
• SUM
• LISTAGG
• STDDEV
• VARIANCE

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S the options that you can
E tableiidentifies
H
Each of the functions accepts an argument. The following h s
use in the syntax: T H S use t
N A to
Function R AM ense Description
K AR le lic Average value of n, ignoring null values
N rab
AVG([DISTINCT|ALL]n)
A
COUNTISH
n s fe Number of rows where expr evaluates to
N
A n-tr a something other than null (count all selected
V
A no rows using *, including duplicates and rows
BH with nulls)
MAX([DISTINCT|ALL]expr) Maximum value of expr, ignoring null values
MIN([DISTINCT|ALL]expr) Minimum value of expr, ignoring null values
STDDEV([DISTINCT|ALL]n) Standard deviation of n, ignoring null values
SUM([DISTINCT|ALL]n) Sum values of n, ignoring null values
LISTAGG Orders data within each group specified in
the ORDER BY clause and then concatenates
the values of the measure column
VARIANCE([DISTINCT|ALL]n) Variance of n, ignoring null values

Oracle Database 12c R2: SQL Workshop I 6 - 6


NIIT LTD

Group Functions: Syntax

SELECT group_function(column), ...


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

FROM table
[WHERE condition];

Group all rows in a column

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
EYou may S
The group function is placed after the SELECT keyword. H h i s have multiple group functions
separated by commas. T H S use t
N A to
Syntax:
R AM ense
K ARfor using
group_function([DISTINCT|ALL]expr)
l e lic
A N rab
Let us look at a few guidelines the group functions:
• I
DISTINCT S Hmakessthe
n fe function consider only nonduplicate values; ALL makes it consider
V ANvalue,
every
n - a
trincluding duplicates. The default is ALL and, therefore, does not need to be
A specified.
no
BH• The data types for the functions with an expr argument may be CHAR, VARCHAR2, NUMBER,
or DATE.
• All group functions ignore null values. To substitute a value for null values, use the NVL,
NVL2, COALESCE, CASE, or DECODE functions.

Oracle Database 12c R2: SQL Workshop I 6 - 7


NIIT LTD

Using the AVG and SUM Functions

You can use the AVG and SUM functions for numeric data.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT AVG(salary), MAX(salary),


MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S that can store numeric data.
E theicolumns
H
You can use the AVG, SUM, MIN, and MAX functions against
S lowest, h s
t and sum of monthly salaries for all
The example in the slide displays the average,
T H
highest, s e
sales representatives. N A to u
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 8


NIIT LTD

Using the MIN and MAX Functions

You can use MIN and MAX for numeric, character, and date data types.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT MIN(hire_date), MAX(hire_date)


FROM employees;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E iand Sdate data types. The example in
You can use the MAX and MIN functions for numeric, H character,
S et h s
the slide displays the most junior and most senior
T H employees.
us
N A t o
The following example displays the employee
A M slaste name that is first and the employee last name that
R ice
is last in an alphabetic list of all employees:
R n
K A
SELECT MIN(last_name), l e lMAX(last_name)
FROM H AN ferab
employees;
NISSUM,
Note: TheAAVG, t r a ns
VARIANCE, and STDDEV functions can be used only with numeric data types.
A V on- be used with LOB or LONG data types.
and MIN cannot
MAX
B H n

Oracle Database 12c R2: SQL Workshop I 6 - 9


NIIT LTD

Using the COUNT Function

• COUNT(*) returns the number of rows in a table:


SELECT COUNT(*)
FROM employees 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

WHERE department_id = 50;

• COUNT(expr) returns the number of rows with non-null values for expr:

SELECT COUNT(commission_pct)
FROM employees 2
WHERE department_id = 50;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
You can use the COUNT function in the following threeHformats:
H S e th
• COUNT(*)
N AT to us
• COUNT(expr)
R AM ense
• COUNT(DISTINCT expr)
K AR le lic
COUNT(*) returns theN numbera ofbrows in a table that satisfy the criteria of the SELECT statement,
H A e r
N IS
including duplicate sf rows containing null values in any of the columns. If a WHERE clause is
rows and
a n
V A n-tr
included in the SELECT statement, COUNT(*) returns the number of rows that satisfy the condition
in theAWHERE clause.
B H no
In contrast, COUNT(expr) returns the number of non-null values that are in the column identified by
expr.
COUNT(DISTINCT expr) returns the number of unique, non-null values that are in the column
identified by expr.
Examples
1. The first example in the slide displays the number of employees in department 50.
2. The second example in the slide displays the number of employees in department 50 who
can earn a commission.

Oracle Database 12c R2: SQL Workshop I 6 - 10


NIIT LTD

Using the DISTINCT Keyword

• COUNT(DISTINCT expr) returns the number of distinct non-null values of expr.


• To display the number of distinct department values in the EMPLOYEES table:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT COUNT(DISTINCT department_id)


FROM employees;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S values in a column.
Use the DISTINCT keyword to suppress the countingHofEany h i s
duplicate
S et
Hdistinct
The example in the slide displays the number
N A Tof
t o usdepartment values that are in the
EMPLOYEES table.
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 11


NIIT LTD

Group Functions and Null Values

• Group functions ignore null values in the column:


SELECT AVG(commission_pct) 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

FROM employees;

• The NVL function forces group functions to include null values:


SELECT AVG(NVL(commission_pct, 0))
2
FROM employees;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
All group functions ignore null values in the column. H
S e th
H us null values.
AT ttooinclude
However, the NVL function forces group functions
N
Examples
R AM ense
K AR based
1. The average is calculated
l e licon only those rows in the table in which a valid value is
A N rab
stored in the COMMISSION_PCT column. The average is calculated as the total commission
that is paid
I S n s fe
Hto all employees divided by the number of employees receiving a commission

V AN n-tra
(four).
2. A The average
o is calculated based on all rows in the table, regardless of whether null values
BH n
are stored in the COMMISSION_PCT column. The average is calculated as the total
commission that is paid to all employees divided by the total number of employees in the
company (20).

Oracle Database 12c R2: SQL Workshop I 6 - 12


NIIT LTD

Lesson Agenda

• Group functions:
– Types and syntax
– Use AVG, SUM, MIN, MAX, COUNT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

– Use the DISTINCT keyword within group functions


– NULL values in a group function
• Grouping rows:
– GROUP BY clause
– HAVING clause
• Nesting group functions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 13


NIIT LTD

Creating Groups of Data

EMPLOYEES

4400
Average salary in the
EMPLOYEES table for
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

9500
each department

3500

6400

10033


s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
Eall group S
Until this point in the discussion, you have observed
S H
that
t h i s functions have treated the table as
H youuneed
one large group of information. At times, however,
TGROUP seclause.
to divide the table of information into
A
A MN se to
smaller groups. This can be done by using the BY

R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 14


NIIT LTD

Creating Groups of Data: GROUP BY Clause Syntax

You can divide the rows in a table into smaller groups by using the GROUP BY clause.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T Sgroups. You can then use the
You can use the GROUP BY clause to divide the rows H in E
a tableh i s
into
group functions to return summary information for
S group.
H each e t
T
A to u s
N
In the syntax:
group_by_expressionR Specifies
AM ensethe columns whose values determine the basis
K AR leforlicgrouping rows
H AN ferab
N IS a ns
A
Let us look
V on-at t
some r guidelines for using the GROUP BY clause:
H• A If youninclude
B well, unless thea group function in a SELECT clause, you cannot select an individual column as
individual column appears in the GROUP BY clause. You receive an error
message if you fail to include the column list in the GROUP BY clause.
• Using a WHERE clause, you can exclude rows before dividing them into groups.
• You can substitute column with an expression in the SELECT statement.
• You must include the columns in the GROUP BY clause.
• You cannot use a column alias in the GROUP BY clause.

Oracle Database 12c R2: SQL Workshop I 6 - 15


NIIT LTD

Using the GROUP BY Clause

All the columns in the SELECT list that are not in group functions must be in the GROUP BY
clause.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id ;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S list that are not group
E in theisSELECT
When using the GROUP BY clause, ensure that all columns H h
S e tin the slide displays the department
functions are included in the GROUP BY clause. T H
The example
us is how this SELECT statement, containing
number and the average salary for eachN A to Here
department.
a GROUP BY clause, is evaluated: AM se
R e n

K
R
The SELECT clauseAspecifies
l e liccolumns to be retrieved as follows:
the
-
H AN fnumber
Department
e rab column in the EMPLOYEES table
S average
- NIThe ns of all salaries in the group that you specified in the GROUP BY clause
A t r a
• AV
H The FROM
n o n-clause specifies the tables that the database must access: the EMPLOYEES table.
B • The WHERE clause specifies the rows to be retrieved. Because there is no WHERE clause, all
rows are retrieved by default.
• The GROUP BY clause specifies how the rows should be grouped. The rows are grouped by
department number, so the AVG function that is applied to the salary column calculates the
average salary for each department.
Note: To order the query results in ascending or descending order, include the ORDER BY clause in
the query.

Oracle Database 12c R2: SQL Workshop I 6 - 16


NIIT LTD

Using the GROUP BY Clause

The GROUP BY column does not have to be in the SELECT list.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT AVG(salary)
FROM employees
GROUP BY department_id ;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S For example, the SELECT
ESELECTisclause.
You do not have to include the GROUP BY column in the H h
H Sforueach
statement in the slide displays the average salaries
T s e tdepartment without displaying the
respective department numbers. WithoutN Adepartment
the to numbers, however, the results do not look
meaningful. M
A ens e
R
R inlithe c ORDER BY clause:
You can also use the groupAfunction
K b l e
H
SELECT AN department_id,
f e r a AVG(salary)
I
NFROMS nsemployees
A t r a
H AV nGROUPo n- BY department_id
B ORDER BY AVG(salary);

Oracle Database 12c R2: SQL Workshop I 6 - 17


NIIT LTD

Grouping by More Than One Column

EMPLOYEES Add the salaries in the EMPLOYEES


table for each job, grouped by
department.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

… a
h a s
)
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E The S
Sometimes, you need to see results for groups within S Hgroups.
t h i s slide shows a report that displays
the total salary that is paid to each job title in T H department.
each
u se
The EMPLOYEES table is grouped firstM byN
A to number, and then by the job title within that
the department
A s e
nin department 50 are grouped together, and a single
R R clerks
grouping. For example, the four stock
i c e
l
KA forblalle stock clerks in the group.
result (total salary) is produced
The following SELECT
N
A statementra returns the result shown in the slide:
S H s f e
A NI -trandepartment_id,
SELECT job_id, sum(salary)
V
A FROM o n
B H n employees
GROUP BY department_id, job_id
ORDER BY job_id;

Oracle Database 12c R2: SQL Workshop I 6 - 18


NIIT LTD

Using the GROUP BY Clause on Multiple Columns

SELECT department_id, job_id, SUM(salary)


FROM employees
WHERE department_id > 40
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

GROUP BY department_id, job_id


ORDER BY department_id;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E by listing Smultiple GROUP BY columns.
H
You can return summary results for groups and subgroups
S e the h i s
t order of the result set. To order the
The GROUP BY clause groups rows but does not T Hguarantee
u s
groupings, use the ORDER BY clause. NA t o
R AMstatement
In the example in the slide, the SELECT e n se that contains a GROUP BY clause is evaluated as
follows:
K AR le lic
• The SELECTA N specifies
clause r a b the columns to be retrieved:
H e
S nsf in the EMPLOYEES table
- NIDEPARTMENT_ID
V A n-tra
A - JOB_ID in the EMPLOYEES table
BH - noThe sum of all salaries in the group that you specified in the GROUP BY clause
• The FROM clause specifies the tables that the database must access: the EMPLOYEES table.
• The WHERE clause reduces the result set to those rows where DEPARTMENT_ID is greater
than 40.
• The GROUP BY clause specifies how you must group the resulting rows:
- First, the rows are grouped by the DEPARTMENT_ID.
- Second, the rows are grouped by JOB ID in the DEPARTMENT_ID groups.
• The ORDER BY clause sorts the results by DEPARTMENT_ID.
Note: The SUM function is applied to the salary column for all job IDs in the result set in each
DEPARTMENT_ID group. Also, note that the SA_REP row is not returned. The DEPARTMENT_ID for
this row is NULL and, therefore, does not meet the WHERE condition.

Oracle Database 12c R2: SQL Workshop I 6 - 19


NIIT LTD

Illegal Queries Using Group Functions

Any column or expression in the SELECT list that is not an aggregate function must be in the
GROUP BY clause:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT department_id, COUNT(last_name) 1


FROM employees;
A GROUP BY clause must be added to
count the last names for each
department_id.

SELECT department_id, job_id, COUNT(last_name)


FROM employees 2
GROUP BY department_id;

s a
Either add job_id in the GROUP BY
clause or remove the job_id column ) h a
from the SELECT list.
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S and group functions (COUNT)
H
1. Whenever you use a mixture of individual items (DEPARTMENT_ID)
SGROUPeBYthclause that specifies the individual
in the same SELECT statement, you must include H a
T BYuclause s is missing, the error message “not a
items (in this case, DEPARTMENT_ID). IfN AGROUP
the t o
single-group group function” appears
R AMand an
e n e (*) points to the offending column. You can
sasterisk
R inlthe
correct the error in the first example
A e ic slide by adding the GROUP BY clause:
K bl
SELECT Ndepartment_id,
H A e r a count(last_name)
FROM
N sf
IS anemployees
VAGROUP n r department_id;
-tBY
H A n o
B
2. Any column or expression in the SELECT list that is not an aggregate function must be in the
GROUP BY clause. In the second example in the slide, JOB_ID is neither in the GROUP BY clause nor
is it being used by a group function, so there is a “not a GROUP BY expression” error. You can correct
the error in the second slide example by adding JOB_ID in the GROUP BY clause.
SELECT department_id, job_id, COUNT(last_name)
FROM employees
GROUP BY department_id, job_id;

Oracle Database 12c R2: SQL Workshop I 6 - 20


NIIT LTD

Illegal Queries Using Group Functions

• You cannot use the WHERE clause to restrict groups.


• You use the HAVING clause to restrict groups.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• You cannot use group functions in the WHERE clause.

SELECT department_id, AVG(salary)


FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;

Cannot use the


WHERE clause to
restrict groups s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
ESELECT S
You cannot use the WHERE clause to restrict groups. The H h i s statement in the example in the
slide results in an error because it uses the WHERET H Sclause
s e t
to restrict the display of the average
u greater than $8,000.
salaries of those departments that have an N Aaverage
t osalary
A M se by using the HAVING clause to restrict groups:
However, you can correct the error
R R
l i c en
in the example
SELECT
N KA ble
department_id, AVG(salary)
FROM HA employeesf e ra
S
NI -tBY s
ndepartment_id
A GROUP r a
H AV HAVING
n o n AVG(salary) > 8000;
B

Oracle Database 12c R2: SQL Workshop I 6 - 21


NIIT LTD

Restricting Group Results

EMPLOYEES

The maximum salary per


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

department when it is
greater than $10,000


s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E way ithat Syou use the WHERE clause to
You use the HAVING clause to restrict groups in the same H h s
H S usalary
restrict the rows that you select. To find the maximum
T s e tin each of the departments that have a
maximum salary greater than $10,000, you N Aneed totodo the following:
M se by grouping by department number.
forAeachedepartment
1. Find the maximum salaryR
R c n
l i
2. Restrict the groups
N KA le
to the departments
b with a maximum salary greater than $10,000.
A
H sfer a
I S
V AN n-tran
A no
BH

Oracle Database 12c R2: SQL Workshop I 6 - 22


NIIT LTD

Restricting Group Results with the HAVING Clause

When you use the HAVING clause, the Oracle server restricts groups as follows:
1. Rows are grouped.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

2. The group function is applied.


3. Groups matching the HAVING clause are displayed.

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S
E to beisdisplayed,
You use the HAVING clause to specify the groups that
S Hare
t h thus further restricting the
groups on the basis of aggregate information.TH se
A u
to you use the HAVING clause:
The Oracle server performs the following
A MNstepssewhen
1. Rows are grouped. R R
l i c en
2. The group function N KA b leto the group.
is applied
A
Hthat matchf a
erthe criteria in the HAVING clause are displayed.
3. The groups
I S s
V
In the syntax, - t r an
ANgroup_condition restricts the groups of rows returned to those groups for which the
A
H condition
specified o n
n is true.
B
The HAVING clause can precede the GROUP BY clause, but it is recommended that you place the
GROUP BY clause first because it is more logical. Groups are formed and group functions are
calculated before the HAVING clause is applied to the groups in the SELECT list.
Note: The WHERE clause restricts rows, whereas the HAVING clause restricts groups.

Oracle Database 12c R2: SQL Workshop I 6 - 23


NIIT LTD

Using the HAVING Clause

SELECT department_id, MAX(salary)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

FROM employees
GROUP BY department_id
HAVING MAX(salary)> 10000 ;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S salaries for departments
E andimaximum
H
The example in the slide displays the department numbers
S et h s
with a maximum salary greater than $10,000.TH
N A t o us
You can use the GROUP BY clause withoutM using
A n s eamust
group function in the SELECT list. If you restrict

R R ice
rows based on the result of a group function, you have a GROUP BY clause as well as the
HAVING clause.
KA ble l
N
A displays
The following example rathe department numbers and average salaries for departments with
S H f e
a maximumN
A
I greater
salary
t r a ns than $10,000:
H AV SELECT
n o n- department_id, AVG(salary)
B FROM employees
GROUP BY department_id
HAVING max(salary)>10000;

Oracle Database 12c R2: SQL Workshop I 6 - 24


NIIT LTD

Using the HAVING Clause

SELECT job_id, SUM(salary) PAYROLL


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

FROM employees
WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S for each job that has a total
Emonthlyissalary
H
The example in the slide displays the JOB_ID and total h
T H Ssales
payroll exceeding $13,000. The example excludes
u s e t
representatives and sorts the list by the
A
total monthly salary.
A MN se to
R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 25


NIIT LTD

Lesson Agenda

• Group functions:
– Types and syntax
– Use AVG, SUM, MIN, MAX, COUNT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

– Use the DISTINCT keyword within group functions


– NULL values in a group function
• Grouping rows:
– GROUP BY clause
– HAVING clause
• Nesting group functions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 26


NIIT LTD

Nesting Group Functions

Display the maximum average salary:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T S in the slide calculates the
E Theiexample
H
Group functions can be nested to a depth of two functions. h s
average salary for each DEPARTMENT_ID and T H Sdisplays
then
u s e tthe maximum average salary.
N Awhentonesting
Note that the GROUP BY clause is mandatory group functions.
A M se
R R lice n
A
A NK rable
I S H sfe
V AN n-tran
A no
BH

Oracle Database 12c R2: SQL Workshop I 6 - 27


NIIT LTD

Quiz Q
Identify the two guidelines for group functions and the GROUP BY clause.
a. You cannot use a column alias in the GROUP BY clause.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

b. The GROUP BY column must be in the SELECT clause.


c. By using a WHERE clause, you can exclude rows before dividing them into groups.
d. The GROUP BY clause groups rows and ensures the order of the result set.
e. If you include a group function in a SELECT clause, you must include a GROUP BY
clause.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E is S
Answer: a, c H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 28


NIIT LTD

Summary

In this lesson, you should have learned how to:


• Use the group functions COUNT, MAX, MIN, SUM, AVG, LISTAGG, STDDEV, and
VARIANCE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• Write queries that use the GROUP BY clause


• Write queries that use the HAVING clause

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
Eas AVG, S
H
There are several group functions available in SQL, such h i s
H S use t
COUNT, MAX, MIN, SUM, LISTAGG,
STDDEV, and VARIANCE. T
You can create subgroups by using the N A BYtclause.
o Further, groups can be restricted using
A MGROUP
s e
the HAVING clause.
R R ice n
K
Place the HAVING and GROUP A l e l after the WHERE clause in a statement. You can have
BY clauses
either the GROUP H
N orrathe
Aclause b HAVING clause first, as long as they follow the WHERE clause.
BY e
sf at the end.
IS BYaclause
Place the ORDER
N tr n
A VA server
The Oracle o n -evaluates the clauses in the following order:
H n
B 1. If the statement contains a WHERE clause, the server establishes the candidate rows.
2. The server identifies the groups that are specified in the GROUP BY clause.
3. The HAVING clause further restricts result groups that do not meet the group criteria in the
HAVING clause.
Note: For a complete list of group functions, see Oracle Database SQL Language Reference for 12c
database.

Oracle Database 12c R2: SQL Workshop I 6 - 29


NIIT LTD

Practice 6: Overview

This practice covers the following topics:


• Writing queries that use group functions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• Grouping by rows to achieve more than one result


• Restricting groups by using the HAVING clause

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.

r
(r tude
s
T
E groups Sof data.
In this practice, you learn to use group functions and H
select h i s
T H S use t
N A to
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

Oracle Database 12c R2: SQL Workshop I 6 - 30

You might also like