0% found this document useful (0 votes)
12 views

Lab06 Mysql

This document discusses SQL group functions such as SUM, AVG, MAX, MIN, and COUNT. It explains how to use the GROUP BY clause to group records by one or more columns and perform aggregate functions on each group. It also covers the HAVING clause, which allows filtering groups based on conditions with group functions. Examples are provided calculating totals, averages, and counts for orders, products, customers and more using GROUP BY with aggregate functions.

Uploaded by

huy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lab06 Mysql

This document discusses SQL group functions such as SUM, AVG, MAX, MIN, and COUNT. It explains how to use the GROUP BY clause to group records by one or more columns and perform aggregate functions on each group. It also covers the HAVING clause, which allows filtering groups based on conditions with group functions. Examples are provided calculating totals, averages, and counts for orders, products, customers and more using GROUP BY with aggregate functions.

Uploaded by

huy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

LAB 06

GROUP QUERIES

❖ Main contents:

- Group Functions: SUM, AVG, MAX, MIN, COUNT


- GROUP BY clause
- HAVING clause

1. Group Functions

SUM function

Sometimes, the information we need is not actually stored in database tables, but we can get it
by handling it from the stored data. For example, we have the OrderDetails table, which stores
information about orders. When we scan this table, we do not know what the total amount of all
the products sold is. However, the SUM function can help us answer this question. First of all,
we see the operation of the SUM function, the data group implementation will be presented in
Part 2.

Example: Calculating the total number of goods currently in stock

SELECT SUM(quantityInStock)
FROM products;

Result:

Or to calculate the total amount we have collected, execute the query as follows:

SELECT SUM(priceEach * quantityOrdered) total


FROM orderdetails;
Result:

AVG function

AVG is used to calculate the average value of an expression. It does not accept NULL values.
We can use AVG to calculate the average price of all products purchased as follows:

SELECT AVG(buyPrice) average_buy_price


FROM Products

Result:

MAX and MIN function

MAX function returns the maximum value and the MIN function returns the smallest value of a
set of values.

MAX(expression)
MIN(expression)

Example: Use MAX and MIN to get the highest price and the lowest price of the product.

SELECT MAX(buyPrice) highest_price,


MIN(buyPrice) lowest_price
FROM Products

Result:

COUNT function

COUNT is a function to count the number, such that we can count the number of products
being sold are as follows:
SELECT COUNT(*) AS Total
FROM products

Result:

Note: another version of the COUNT function uses a column name as a parameter. If this
method is used, it will only count the rows whose value is NOT NULL.

2. GROUP BY statement
GROUP BY statement is used to combine records with the same value in one or more columns,
into a collection. If GROUP BY exists, it must follow the WHERE or FROM statement. Following
the GROUP BY keyword is a list of expressions, separated by commas.

SELECT col1, col_2, ... col_n, group_function(expressions)


FROM table name
WHERE condition
GROUP BY col_1, col_2, ... col_n
ORDER BY column list

By definition, the group function allows us to perform a calculation on a record set and return a
value. The group function ignores NULL values when performing calculations, except for the
COUNT function. The group function is often used with the GROUP BY statement of the SELECT
statement.

Example: Suppose we want to divide orders by groups depending on the status of the orders,
we can do the following:

SELECT status
FROM orders
GROUP BY status;
Result:

The group functions are used with GROUP BY to perform calculations on each group of
records and return a unique value for each row.

Example: If we want to know how many orders are in each status group, we can use the
COUNT function as follows:

SELECT status, COUNT(*)


FROM orders
GROUP BY status;

Result:

Example: If we want to know how many products are in each product line:

SELECT productLine, COUNT(*)


FROM products
GROUP BY productline;
Example: To get the total amount for each product sold, we just need to use the SUM function
and the product group. Here is the query:

SELECT productCode, SUM(priceEach * quantityOrdered) total


FROM orderdetails
GROUP by productCode;

Result:

Example: Suppose we want to see the results of the above query, shown in ascending order we
do the following:

SELECT productCode, SUM(priceEach * quantityOrdered) total


FROM orderdetails
GROUP by productCode
ORDER BY total DESC;
Result:

Note: the difference between GROUP BY in MySQL and ANSI SQL

MySQL follows the ANSI SQL standard. However, there are 2 differences when using
GROUP BY in MySQL as follows:

• In ANSI SQL, GROUP BY must be executed for all the columns that appear in the
SELECT statement. MySQL does not require that, can include more columns in the
SELECT statement and does not force them to appear in the GROUP BY statement.
• MySQL also allows the arrangement of groups in the order of the calculation results; the
default is descending.

3. HAVING clause

HAVING is also a clause that may or may not appear in the SELECT statement. It indicates
whether a filter on the data is a group of records or the result of the group function
implementation. HAVING is often used in conjunction with GROUP BY, so that the filter
condition is only applied on the columns that appear in the GROUP BY clause. If HAVING is not
included with GROUP BY, then it is as meaningful as WHERE. Note that HAVING applies to
groups of records, while WHERE applies to each individual record.
Example: Use the GROUP BY clause to get all orders, the number of items sold, and the total
value of each order as follows:

SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceEach * quantityOrdered) AS total
FROM orderdetails
GROUP BY ordernumber;

Now, it is possible to request that only orders with a total value greater than $1000 be displayed
using HAVING as follows:

SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceEach * quantityOrdered) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000;
We use the alias for the sum column (priceEach * quantityOrdered) as total, so in the HAVING
clause, we just need to use that alias instead of Typing SUM (priceEach) again.

A combination condition can be used in the HAVING clause with the OR, AND operators.

Example: If we want to know that orders total greater than $1000 and have more than 600 items
in them, we can use the following query:

SELECT ordernumber,
sum(quantityOrdered) AS itemsCount,
sum(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000 AND itemsCount > 600;
Result:

❖ Practice Exercises:
1. Get the names of the cities and the number of customers in each city.
2. Get the number of orders in March 2005. Get the number of orders for each month in
2005.
3. Get the 10 order numbers that have the most valuable price.
4. Get the product line and the total quantity in stock of that group.
5. Get the customer number and the total amount that customer paid.

You might also like