Worksheet4 Aggregation
Worksheet4 Aggregation
SQL Aggregation
1) Functions
SQL provides some built-in functions for performing data aggregation and grouping. The main ones are:
- A HAVING clause.
Basic syntax:
1
• Try the following query to obtain various statistics on the product prices:
• We can better format all those prices using the CAST() conversion function:
SELECT CAST(MIN(price) AS decimal (6, 2)) AS "Lowest price ", CAST(AVG(price) AS decimal (6,
2)) AS Average, CAST(MAX(price) AS decimal (6, 2)) AS Highest, CAST(SUM(price) AS decimal (7,
2)) AS "Total sum " FROM Product;
• Try the following query to obtain how many products cost at least 10 Dhs:
• Try the following query to obtain the total value of all products in inventory.
Practice problems
• Write the SQL statement to count the number of products that have no discount
• Write the SQL query to obtain the number of vendors living in UK and supplying some products that
cost at least 10 DHs.
GROUP BY is used in conjunction with the aggregate functions to group a selected set of rows into a set
of summary rows by the values of one or more columns or expressions. One row is returned for each
group.
Basic syntax:
We can use the following query to display, for every vendor, their products’ average price:
2
Practice problems
• For each invoice, display the invoice number and the total amount of that invoice.
• For each customer, display the customer code and the total number of invoices that were issued for that
customer (also consider the customers that have no invoices).
• Display the vendor code, vendor name and the total product value for all the products that have no discount
supplied by each vendor.
The HAVING clause is used to restrict the aggregated results returned based on a post- aggregation
condition; it is used in conjunction with aggregate functions to select the result- set by some condition.
where aggregate_condition in the HAVING clause is a logical expression constraining on some condition
on the aggregated results.
We can use the following query to display information about every vendor whose product price average is
more than 10 dirhams. The information displayed includes the vendor code, the number of products and
the average price of the products supplied by each vendor:
SELECT vendorCode, COUNT(*) AS "Product Count", AVG(price) AS "Avg price" FROM Product
GROUP BY vendorCode
HAVING AVG(price) > 10;
Practice Problems
Practice Problems