In MySQL, aggregate functions are used to perform calculations on multiple rows of a dataset and return a single value. Common aggregate functions include COUNT, SUM, and AVG. Here's how to use each one:
The COUNT function counts the number of rows that match a specified condition. It can be used on columns or as a wildcard.
The SUM function calculates the total of a numeric column.
The AVG function computes the average value of a numeric column.
<?php
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// COUNT Example
$count_query = "SELECT COUNT(*) as total FROM users WHERE active = 1";
$result = $conn->query($count_query);
$count = $result->fetch_assoc();
echo "Active users: " . $count['total'];
// SUM Example
$sum_query = "SELECT SUM(salary) as total_salary FROM employees";
$result = $conn->query($sum_query);
$sum = $result->fetch_assoc();
echo "Total Salary: " . $sum['total_salary'];
// AVG Example
$avg_query = "SELECT AVG(age) as average_age FROM customers";
$result = $conn->query($avg_query);
$avg = $result->fetch_assoc();
echo "Average Age: " . $avg['average_age'];
$conn->close();
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?