A3.3.4
Construct calculations within a database using SQL’s aggregate functions
Aggregate functions allow calculations to be performed on data in a database.
- Aggregate functions allow calculations to be performed on data in a database.
AVG
SELECT AVG(attribute) FROM table_name;
SELECT AVG(age) FROM student;
SELECT AVG(score)
FROM student
WHERE score > 87;
COUNT
SELECT COUNT(attribute) FROM table_name;
SELECT COUNT(StudentID) FROM Students;
SUM
SELECT SUM(attribute) FROM table_name;
SELECT SUM(score) FROM Students;
MIN and MAX
SELECT MIN(attribute) FROM table_name;
SELECT MAX(attribute) FROM table_name;
SELECT MIN(score) FROM Students;
SELECT MAX(score) FROM Students;
Aggregate functions with GROUP BY
SELECT subject, AVG(score) AS average_score
FROM Subjects
GROUP BY subject;
SELECT CustomerCountry, COUNT(CustomerID)
FROM Customer
GROUP BY CustomerCountry;
Aggregate functions with HAVING
SELECT CustomerCountry, COUNT(CustomerID)
FROM Customer
GROUP BY CustomerCountry
HAVING COUNT(CustomerID) > 2;