Lab 7 - (Queries II)
Lab 7 - (Queries II)
Lab (7)
We will use a new simple database schema for an online store. The relationships and data are
shown below:
Note: There are 4 main tables: 1:M relationship between Customer and Order & Product_type and
Product, as well as a M:N relationship between Orders and Product tables.
1
Customer table:
Orders table:
Product table:
Order_Product table:
2
Product_Type table:
1. Group By Clause:
The GROUP BY clause summaries identical rows into a single/distinct group and
returns a single row with the summary for each group, by using appropriate
aggregate function in the SELECT list, like COUNT(), SUM(), MIN(), MAX(),
AVG(), etc.
GROUP BY clause works on the rows returned by SELECT query.
SELECT <column_name>
FROM <table name>
[WHERE <filter condition>]
[GROUP BY <column/ column list>]
3
Query 2: To list the number of customers in each city:
Code:
Query 3: In each city, how many males and how many females?
Code:
SELECT City, Gender, COUNT(*) AS NumberOfCustomers
FROM Customer
GROUP BY City, Gender
ORDER BY City, Gender;
Note: There will be an error if we removed either City or Gender from the
GROUP BY statement. Result:
4
Query 4: How many orders have been done in each year?
Code:
SELECT YEAR(Order_date) AS orderYear, count(*)
AS NumberOfOrders
FROM Orders
GROUP BY YEAR(Order_date)
ORDER BY count(*);
Result:
2. Having Clause:
The HAVING clause works as a filter on top of grouped rows returned by
the GROUP BY clause (because the WHERE keyword could not be used
with aggregate functions).
This clause cannot be replaced by WHERE clause and vice-versa.
SELECT <column_name>
FROM <table name>
[WHERE <filter condition>]
[GROUP BY <column/column list>]
[HAVING <filter on aggregate column>]
5
Query 2: To retrieve how many products have the same price (only if
they are more than 2 products) Code:
SELECT COUNT(Product_ID) AS NumberOfProducts,
Product_Price
FROM Product
GROUP BY Product_Price
HAVING COUNT(Product_ID) > 2;
Result:
Do It Yourself
1. Retrieve the cheap products (cost less than 15) with a large stock (greater than
600)
Expected result:
Expected result:
Expected result:
4. Retrieve the number of customers in each city (only include cities that have
more than one customer)
6
Expected result: