Lab 10

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Lab # 10

Group by clause and Having statement

An SQL group function or aggregate functions performs an operation on a group of rows and
returns a single result. You may want to retrieve group of item-prices and return total-
price. This type of scenario is where you would use a group function. The following table is
summary of some SQL group functions & query examples

Function Description Query Example

AVG(fieldname) Returns average value of a column SELECT avg(price)FROM inventory;

SELECT count(product_id)FROM
COUNT(fieldname) Returns number of items in table or
product;
COUNT(*) queried items
SELECT count(*) FROM product;

MAX(fieldname) Returns maximum value of a column SELECT max(price)FROM inventory;

MIN(fieldname) Returns minimum value of a column SELECT min(price)FROM inventory;

SUM(fieldname) Returns total value of a column SELECT sum(price)FROM inventory;

SELECT stddev(price)FROM
STDDEV Returns standard deviation
inventory;

SELECT variance(price)FROM
VARIANCE Returns the variance
inventory;

To use a group function in a SQL query, list the function name followed by numeric column
name within parentheses. AVG averages the column, COUNT counts the number of items, MAX
returns maximum number of the column, and MIN returns minimum number of the column.

Examples of Some Functions

The following is query to retrieve total price, average price, maximum price, and minimum price
from the table "product" assuming the product table has the following values.
PRODUCT

Product ID Name Description Price Cost

100000000 Printer Inkjet 300 colour Printer 120 80

100000001 Printer 1220CXI Inkjet Printer 200 130

100000002 Printer Photo 890 Injet Printer 250 200

100000003 Printer Photo 890 Injet Printer 300 270

Using AVG and SUM Functions

• AVG and SUM are used for numeric data type

Example

SQL> SELECT AVG (sal), SUM (sal)

2 FROM emp

3 WHERE sal= 1250;

Result

AVG (SAL) SUM (SAL)

------------- -------------
1400 5600

Using MIN and MAX Functions

• MIN and MAX group functions can be used for any data type

Example

SQL> SELECT MIN (hiredate), MAX (hiredate)

2 FROM emp;

Result

MIN(HIRED MAX(HIRED

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

17-DEC-80 12-JAN-83

Using the COUNT Function

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

Example

SQL> SELECT COUNT (*)


2 FROM emp

3 WHERE deptno = 30;

Result

COUNT (*)

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

Group Functions and Null Values

All group functions except COUNT (*) ignore null values in the column. In example below, the
average is calculated based only on the rows in the table where a valid value is stored in the
COMM column. The average is calculated as total commission being paid to all employees
divided by the number of employees receiving commission (4).

Example

SQL> SELECT AVG (comm)

2 FROM emp;

Result

AVG(COMM)

---------

550
 SELECT sum (price)
FROM product;
This statement will return the total amount for the column price which is 870.

 SELECT avg (price)


FROM product;
This statement will return the average amount for the column price which is 870/4 or
217.50.

 SELECT max (price)


FROM product;
This statement will return the maximum amount for the column price which is 300.

 SELECT min (price)


FROM product;
This statement will return the minimum amount for the column price which is 120.

 SELECT count (*)


FROM product;
This statement will return the number of items in table which is 4.

GROUP BY Clause with Group Functions

Group By is used to categorize the retrieved data. For example, you may want to list sales of
each product identified by product id. To do this, the following is Group By example that lists

The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to
provide means of grouping the result dataset by certain database table column(s).

The best way to explain how and when to use the SQL GROUP BY statement is by example, and
that’s what we are going to do.

Consider the following database table called EmployeeHours storing the daily hours for each
employee of a factious company:

Employee Date Hours

John Smith 5/6/2004 8

Allan Babel 5/6/2004 8


Tina Crown 5/6/2004 8

John Smith 5/7/2004 9

Allan Babel 5/7/2004 8

Tina Crown 5/7/2004 10

John Smith 5/8/2004 8

Allan Babel 5/8/2004 8

Tina Crown 5/8/2004 9

If the manager of the company wants to get the simple sum of all hours worked by all
employees, he needs to execute the following SQL statement:

SELECT SUM (Hours)


FROM EmployeeHours

But what if the manager wants to get the sum of all hours for each of his employees?
To do that he need to modify his SQL query and use the SQL GROUP BY statement:

SELECT Employee, SUM (Hours)


FROM EmployeeHours
GROUP BY Employee

The result of the SQL expression above will be the following:

Employee Hours

John Smith 25

Allan Babel 24

Tina Crown 27

As you can see we have only one entry for each employee, because we are grouping by the
Employee column.
The SQL GROUP BY clause can be used with other SQL aggregate functions, for example SQL
AVG:

SELECT Employee, AVG (Hours)


FROM EmployeeHours
GROUP BY Employee

The result of the SQL statement above will be:

Employee Hours

John Smith 8.33

Allan Babel 8

Tina Crown 9

In our Employee table we can group by the date column too, to find out what is the total
number of hours worked on each of the dates into the table:

SELECT Date, SUM (Hours)


FROM EmployeeHours
GROUP BY Date

Here is the result of the above SQL expression:

Date Hours

5/6/2004 24

5/7/2004 27

5/8/2004 25

SQL HAVING
• Sometimes we want to retrieve the values of these functions for only those groups that
satisfy certain conditions

• The HAVING-clause is used for specifying a selection condition on groups (rather than on
individual tuples)

What is SQL HAVING?

• The SQL HAVING clause enables conditions at the aggregate level. It is used instead of
the WHERE clause when Aggregate Functions are used.

Why Use SQL HAVING?

• The HAVING clause is used to SELECT information based aggregate information. For
example, one may want to list sales representatives that have sales totaling over
$10,000. This is very useful for analytical reporting.

SYNTAX
SELECT <column_name1>, <column_name2> <aggregate_function>
FROM <table_name>
GROUP BY <column_name1>, <column_name2>
HAVING <having_condition>

EXAMPLE

SELECT job, count (*), 12*AVG (SAL)

FROM EMP

GROUP BY JOB

HAVING COUNT (*)> 2

Lab Tasks

1. Show the total number of employees in each department.


2. Show the total number of employees in an organization in department 20.

3. Show the department number that have less than 5 employees.

4. Show the department names of employees and the number of employees in the
department.

5. Show the department names that have less than 5 employees.

6. Show the total salary for the whole organization.


7. Show the total salary for each department.

8. Show the total salary for department number 30.

9. Show the department number that have budget more than 10,000

10. Show the department name and location that have budget more than 10,000
11. Display the number of employees department-wise and job-wise. The output look like as:
DEPTNO JOB COUNT (*)
------- --------- ---------
10 CLERK 1
10 MANAGER 1
10 PRESIDENT 1
20 CLERK 2
20 ANALYST 2
20 MANAGER 1
30 CLERK 1
30 MANAGER 1
30 SALESMAN 4

12. Display the highest and lowest salaries department wise. The output look like as:
DEPTNO LOWEST HIGHEST
1 1200 52000
2 800 6950
3 4560 19856
13. Display the department-wise total salary given to the employees of an organization.

14. Display the dept-wise number of employees working in an organization.

15. Display the departments that have less than 5 employees

16. Display the departments that have at least 1 employee

You might also like