在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