Day 15: Aggregate Functions
Introduction:
Aggregate functions perform calculations on a set of values and return a single value. They are useful for summarizing data.
Key Concepts:
COUNT(): Returns the number of rows.
SUM(): Returns the total sum of a numeric column.
AVG(): Returns the average value of a numeric column.
MIN(): Returns the smallest value in a set.
MAX(): Returns the largest value in a set.
SQL Commands and Examples:
COUNT() Function:
Count the number of rows in a table.
-- Count the number of students
SELECT COUNT(*) AS TotalStudents FROM Students;
SUM() Function:
Calculate the total sum of a numeric column.
-- Calculate the total credits of all courses
SELECT SUM(Credits) AS TotalCredits FROM Courses;
AVG() Function:
Calculate the average value of a numeric column.
-- Calculate the average age of students
SELECT AVG(Age) AS AverageAge FROM Students;
MIN() Function:
Find the smallest value in a set.
-- Find the minimum salary in the Employees table
SELECT MIN(Salary) AS MinSalary FROM Employees;
MAX() Function:
Find the largest value in a set.
-- Find the maximum salary in the Employees table
SELECT MAX(Salary) AS MaxSalary FROM Employees;
Practice Exercise:
Use the Courses and Students tables.
Write a query to count the number of courses.
Write a query to calculate the total and average credits of all courses.
Write a query to find the maximum and minimum age of students.
Write a query to find the maximum salary in the Employees table.
Write a query to count the number of employees in each department.
-- Count the number of courses
SELECT COUNT(*) AS TotalCourses FROM Courses;
-- Calculate the total and average credits of all courses
SELECT SUM(Credits) AS TotalCredits, AVG(Credits) AS AverageCredits FROM Courses;
-- Find the maximum and minimum age of students
SELECT MAX(Age) AS MaxAge, MIN(Age) AS MinAge FROM Students;
-- Find the maximum salary in the Employees table
SELECT MAX(Salary) AS MaxSalary FROM Employees;
-- Count the number of employees in each department
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department;
Understanding and utilizing aggregate functions allows you to summarize and analyze your data effectively.
0 Comments