-- 创建员工表 CREATE TABLE employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, department TEXT NOT NULL, salary REAL ); -- 创建部门字段的索引以优化GROUP BY查询 CREATE INDEX idx_department ON employees(department); -- 插入示例数据 INSERT INTO employees (name, department, salary) VALUES ('张三', '人力资源', 60000), ('李四', '工程部', 75000), ('王五', '人力资源', 50000), ('赵六', '工程部', 80000), ('钱七', '销售部', 55000), ('孙八', '销售部', 45000), ('周九', '工程部', 70000), ('吴十', '人力资源', 48000), ('郑十一', '销售部', 62000), ('刘十二', '工程部', 85000);
聚合函数的基本用法
以下是一些基本用法示例:
-- 计算总行数 SELECT count(*) FROM employees; -- 计算工资总和 SELECT sum(salary) FROM employees; -- 计算平均工资 SELECT avg(salary) FROM employees; -- 找出最高工资 SELECT max(salary) FROM employees; -- 找出最低工资 SELECT min(salary) FROM employees; -- 连接所有员工姓名 SELECT group_concat(name, ', ') FROM employees;
GROUP BY 子句与聚合函数
GROUP BY 子句通常与聚合函数一起使用,用于对数据进行分组计算:
-- 按部门计算平均工资 SELECT department, avg(salary) AS avg_salary FROM employees GROUP BY department; -- 计算每个部门的员工数量 SELECT department, count(*) AS employee_count FROM employees GROUP BY department;
HAVING 子句
HAVING 子句用于过滤分组后的结果:
-- 找出平均工资超过 50000 的部门 SELECT department, avg(salary) AS avg_salary FROM employees GROUP BY department HAVING avg_salary > 50000;
窗口函数中的聚合
从 SQLite 3.25.0 版本开始,支持窗口函数,这允许在更复杂的场景中使用聚合函数:
-- 计算每个员工的工资和部门平均工资 SELECT name, salary, avg(salary) OVER (PARTITION BY department) AS dept_avg_salary FROM employees; -- 计算累计工资总和 SELECT name, salary, sum(salary) OVER (ORDER BY salary) AS running_total FROM employees;
自定义聚合函数
SQLite 允许创建自定义聚合函数。这通常通过 C API 或特定语言的绑定来实现。例如,可以创建一个计算中位数的函数:
SELECT count(CASE WHEN salary > 50000 THEN 1 END) AS high_salary_count, count(CASE WHEN salary <= 50000 THEN 1 END) AS low_salary_count FROM employees;
嵌套聚合
在某些情况下可以嵌套使用聚合函数:
SELECT avg(total_salary) AS avg_dept_total FROM ( SELECT department, sum(salary) AS total_salary FROM employees GROUP BY department );
聚合函数与子查询
SELECT name, salary, (SELECT avg(salary) FROM employees) AS overall_avg_salary FROM employees;
聚合函数与 NULL 值
聚合函数处理 NULL 值的方式:
count(*):包括 NULL 值在内的所有行。
count(column):不包括 NULL 值。
sum(), avg(), max(), min():忽略 NULL 值。
示例:
SELECT count(*) AS total_rows, count(salary) AS salary_count, avg(salary) AS avg_salary FROM employees;