在MySQL中,可以使用聚合函数(Aggregate Functions)来对一组值进行计算和汇总。以下是一些常用的聚合函数及其用法:
SELECT COUNT(*) FROM table_name; // 计算表中的行数
SELECT COUNT(column_name) FROM table_name; // 计算某列非空值的数量
SELECT SUM(column_name) FROM table_name; // 计算某列数值的总和
SELECT AVG(column_name) FROM table_name; // 计算某列数值的平均值
SELECT MIN(column_name) FROM table_name; // 找到某列的最小值
SELECT MAX(column_name) FROM table_name; // 找到某列的最大值
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name;
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name HAVING condition;
以下是一个简单的示例,展示了如何使用聚合函数对某列进行求和、计数和平均值计算:
-- 员工表
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
age INT,
salary DECIMAL(10, 2)
);
-- 插入示例数据
INSERT INTO employees (name, age, salary) VALUES ('张三', 30, 5000);
INSERT INTO employees (name, age, salary) VALUES ('李四', 28, 6000);
INSERT INTO employees (name, age, salary) VALUES ('王五', 35, 7000);
INSERT INTO employees (name, age, salary) VALUES ('赵六', 29, 8000);
-- 计算工资总和
SELECT SUM(salary) as total_salary FROM employees; // 结果:total_salary = 26000
-- 计算员工数量
SELECT COUNT(*) as employee_count FROM employees; // 结果:employee_count = 4
-- 计算平均工资
SELECT AVG(salary) as average_salary FROM employees; // 结果:average_salary = 6500