Oracle Lab 7
Oracle Lab 7
Functions
GROUP BY
HAVING
1
What Are Group Functions ?
DEPTNO SAL
--------------------- ---------------
10 2450
10 5000
10 1300
20 800
20 1100 “Maximum salary MAX(SAL)
20 3000 in the EMP table”
---------------
20 3000
5000
20 2975
30 1600
30 2850
30 1250
30 950
30 1250
30 1250
2
Using Group Functions
SELECT [COLUMN,] group_function(column)
FROM table
[WHERE condition]
[GROUP BY column
[ORDER BY column];
3
Using MIN and MAX Functions
MIN(HIRED MAX(HIRED
---------------- -----------------
17-DEC-80 12-JAN-83
4
Using AVG and SUM Functions
5
Using the COUNT Function
SELECT COUNT(*)
FROM emp
WHERE deptno = 30;
6
Group Functions and Null Values
SELECT AVG(comm)
FROM emp;
7
Creating Groups of Data
DEPTNO SAL
--------------------- ---------------
10 2450
10 5000 2916.6667
10 1300
20 800
20 1100 average
MAX(SAL)
salary in
20 3000 2175 EMP table ---------------
20 3000 for each 5000
20 2975 department
30 1600
30 2850
30 1250 1566.6667
30 950
30 1250
30 1250 8
Creating Groups of Data :
GROUP BY Clause
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group-by-expression]
[ORDER BY column];
9
Guidelines
• If you include a group function in a SELECT clause, you
cannot select individual results as well unless the individual
column appears in the GROUP BY clause. You will receive
an error message if you fail to include the column list.
10
Using the GROUP BY Clause
11
Using the GROUP BY Clause
SELECT AVG(sal)
FROM emp
GROUP BY deptno;
Grouping by More Than One Column
DEPTNO JOB SAL
------------ ---------------- ---------------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300 DEPTNO JOB SUM(SAL)
20 CLERK 800 ------------ ---------------- ---------------
20 CLERK 1100 10 CLERK 1300
20 ANALYST 3000 10 MANAGER 2450
20 ANALYST 3000 10 PRESIDENT 5000
20 MANAGER 2975 20 ANALYST 6000
30 SALESMAN 1600 .....
30 MANAGER 2850 9 rows selected.
30 SALESMAN 1250
30 CLERK 950
30 SALESMAN 1250
30 SALESMAN 1250
15
Illegal Queries Using Group Functions
• You cannot use the WHERE clause to restrict groups.
• You use the HAVING clause to restrict groups.
17
Excluding Group Results :
HAVING Clause
Use the HAVING clause to restrict groups
• Rows are grouped.
• The group function is applied.
• Groups matching the HAVING clause are displayed.
DEPTNO MAX(SAL)
------------------- -------------------
10 5000
20 3000
19
Using the HAVING Clause
JOB MAX(SAL)
-------------- -------------------
ANALYST 6000
MANAGER 8275
20