SQL 3 - Group by Clause
SQL 3 - Group by Clause
Aggregate Queries
Information Systems and Databases
1
SQL 3
Objectives
• To understand how data can be grouped for aggregated
queries
• To use aggregate functions in retrieving data
• To filter aggregated data using the HAVING clause
2
SQL 3
Recap – SELECT statement
SQL 3 3
Aggregate/Group Functions
SQL 3 4
AVG (column)
• Calculates the average value of a numeric
column.
Eg: To work out the average commission
(comm) for all employees in the ‘emp’ table:
SELECT AVG(total)
FROM ord;
SQL 3 6
SUM(column)
• Calculates the total of a numeric
column.
Eg: To work out the total salary for all
employees in the ‘emp’ table:
SELECT SUM(sal)
FROM emp;
SQL 3 7
MIN(column), MAX(column)
SQL 3 8
MIN(column), MAX(column)
Can also be used with non-numeric
columns:
SELECT MAX(ename), MIN(ename)
FROM emp;
SQL 3 9
COUNT(column) , COUNT(*)
SQL 3 10
COUNT (col) and COUNT(*)
Empno ename mgr ......
7369 SMITH 7902
7499 ALLEN 7698 Doesn’t count
7521 WARD 7698 the null
7839 KING
7878 ADAMS 7788
7788 SCOTT 7698
SELECT COUNT(*)
FROM EMP;
Gives: COUNT(*)
-------------
6
SELECT COUNT(mgr)
FROM EMP;
Gives: COUNT(mgr)
-------------
5 3
SQL 11
USING ‘GROUP BY’ CLAUSE
10 ......
20 ......
30 ......
SQL 3 12
GROUP BY
CLERK ......
SALESMAN ......
MANAGER ......
ANALYST ......
PRESIDENT ......
GROUP BY mgr gives 7 lines of output:
7902 ......
7698 ....
7839 ......
7566 ......
7788 ......
7566 ......
7782 ......
SQL 3 13
Eg: List the maximum salary for each department:
SQL 3 14
‘GOLDEN RULE’
SQL 3 15
‘GOLDEN RULE’
SQL 3 17
GROUP BY- EXAMPLES
SQL 3 18
USING EXPRESSIONS IN ‘GROUP BY’
SQL 3 19
USING ‘WHERE’ CLAUSE
SQL 3 23
To select the total salary for each dept, but only for those depts
with a total salary of over £165,000: without the HAVING clause:
SQL 3 24
‘WHERE’ and ‘HAVING’
• Eg: to list the maximum salary of each
department, excluding department 20 or any
departments with an average salary of 30000 or
more:
SELECT deptno, MAX(sal)
FROM emp
WHERE deptno != 20
GROUP BY deptno
HAVING AVG(sal) < 30000
Note - Avg(sal) does not have
to appear in the ‘select ‘ line.
SQL 3 25
Adding the ORDER BY Clause
• The ORDER BY clause comes after any HAVING
clause and must use either a group by function or a
column in the GROUP BY clause, eg
SELECT deptno, COUNT(*), AVG(sal)
FROM emp
GROUP BY deptno
HAVING COUNT(empno)> 1
ORDER BY COUNT(*);
(ORDER BY clause could also be written as ORDER BY 2)
SQL 3 26
TRY THE FOLLOWING (Using the EMP table)
SQL 3 29
Further Reading
Casteel, J (2016) – Oracle 12c SQL
Ch. 11 ‘Group Functions’
SQL 3 30