MySQL Practical 7
MySQL Practical 7
MySQL Practical 7
• The GROUP BY statement is used with aggregate functions (COUNT, MAX, MIN, SUM, AVG)
to group the result-set by one or more columns.
Exercise
1. Create a table to record CUIT201 marks. Use information given in the following table. Select
appropriate primary key.
COUNT
• COUNT function counts the number of values in a column.
• MySQL Aggregate Functions - COUNT()
• COUNT(*) counts all the rows in a table, regardless of whether there are nulls present.
Otherwise, each function ignores nulls.
• If an aggregate function is applied to an empty set of values, then COUNT returns zero and
the other aggregate functions return null.
COUNT Syntax
SELECT COUNT(*)
Page 1|5
M. Chinyuku Database Systems 2023
FROM cuit201;
3. Find number of students who got marks greater than 60 for Test 1
SELECT COUNT(*) AS Total_Test1
FROM cuit201
WHERE Test1>60;
you want to know the number of values in a given column (excluding null values), specify
the column name rather than the asterisk.
SELECT COUNT( Test1) AS Total_Test1
FROM cuit201
WHERE Test1>60;
5. If pass mark is 55. Find the number of students who failed both the test and assignment
SELECT COUNT(*) AS Fail
FROM cuit201
WHERE Assignment1<55 AND Test1 <55;
DISTINCT is used if duplicate values are to be eliminated before the function is applied. The
DISTICT keyword can be added to the COUNT function
6. Find the number of marks less than 55 for test1
Page 2|5
M. Chinyuku Database Systems 2023
MIN
• MIN finds the smallest value in a column.
• MySQL Aggregate Functions - MIN()
SELECT MIN(Test1)
FROM cuit201;
MAX
• MAX finds the largest value in a column.
• MySQL Aggregate Functions - MAX()
8. Find the maximum mark for Assignment 1
SELECT MAX(Assignment1)
FROM cuit201;
SUM
• SUM sums the values in a column.
• MySQL Aggregate Functions - SUM()
AVG
• AVG calculates the average of the values in a column.
• MySQL Aggregate Functions - AVG()
10. Find the average of assignment 1 marks
11. Find the total and average marks for students with names Anesu.
Page 3|5
M. Chinyuku Database Systems 2023
Group by Clause
Groups rows in an intermediate results table where the values in those rows are the same
for one or more columns
Customer
Account FirstName LastName Address City
A1234 Mary Jonas 10 Second Street Chinhoyi
B1245 John Jonas 101 first street Harare
C1234 Mary Javu Nguruve avenue Chinhoyi
A1100 James Ruke 11th Street Chinhoyi
A3210 Gewa Mupo 24 Wine Street Bulawayo
B2200 Mary Donni 32 Magamba Way Harare
C4000 Jaji Chasi 41 Shepure Street Masvingo
D1213 Anesu Lunga 12 Mopane Road Karoi
13. Count the number of customers with addresses in each city. List the cities.
Page 4|5
M. Chinyuku Database Systems 2023
15. List, in alphabetical order, the ProductID and the average price for each product for selected
products P100 and P123 having an average price greater than 50
Page 5|5