-- 創(chuàng)建員工表 CREATE TABLE employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, department TEXT NOT NULL, salary REAL ); -- 創(chuàng)建部門字段的索引以優(yōu)化GROUP BY查詢 CREATE INDEX idx_department ON employees(department); -- 插入示例數(shù)據(jù) INSERT INTO employees (name, department, salary) VALUES ('張三', '人力資源', 60000), ('李四', '工程部', 75000), ('王五', '人力資源', 50000), ('趙六', '工程部', 80000), ('錢七', '銷售部', 55000), ('孫八', '銷售部', 45000), ('周九', '工程部', 70000), ('吳十', '人力資源', 48000), ('鄭十一', '銷售部', 62000), ('劉十二', '工程部', 85000);
聚合函數(shù)的基本用法
以下是一些基本用法示例:
-- 計(jì)算總行數(shù) SELECT count(*) FROM employees; -- 計(jì)算工資總和 SELECT sum(salary) FROM employees; -- 計(jì)算平均工資 SELECT avg(salary) FROM employees; -- 找出最高工資 SELECT max(salary) FROM employees; -- 找出最低工資 SELECT min(salary) FROM employees; -- 連接所有員工姓名 SELECT group_concat(name, ', ') FROM employees;
GROUP BY 子句與聚合函數(shù)
GROUP BY 子句通常與聚合函數(shù)一起使用,用于對數(shù)據(jù)進(jìn)行分組計(jì)算:
-- 按部門計(jì)算平均工資 SELECT department, avg(salary) AS avg_salary FROM employees GROUP BY department; -- 計(jì)算每個(gè)部門的員工數(shù)量 SELECT department, count(*) AS employee_count FROM employees GROUP BY department;
HAVING 子句
HAVING 子句用于過濾分組后的結(jié)果:
-- 找出平均工資超過 50000 的部門 SELECT department, avg(salary) AS avg_salary FROM employees GROUP BY department HAVING avg_salary > 50000;
-- 計(jì)算每個(gè)員工的工資和部門平均工資 SELECT name, salary, avg(salary) OVER (PARTITION BY department) AS dept_avg_salary FROM employees; -- 計(jì)算累計(jì)工資總和 SELECT name, salary, sum(salary) OVER (ORDER BY salary) AS running_total FROM employees;
自定義聚合函數(shù)
SQLite 允許創(chuàng)建自定義聚合函數(shù)。這通常通過 C API 或特定語言的綁定來實(shí)現(xiàn)。例如,可以創(chuàng)建一個(gè)計(jì)算中位數(shù)的函數(shù):
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;
嵌套聚合
在某些情況下可以嵌套使用聚合函數(shù):
SELECT avg(total_salary) AS avg_dept_total FROM ( SELECT department, sum(salary) AS total_salary FROM employees GROUP BY department );
聚合函數(shù)與子查詢
SELECT name, salary, (SELECT avg(salary) FROM employees) AS overall_avg_salary FROM employees;
聚合函數(shù)與 NULL 值
聚合函數(shù)處理 NULL 值的方式:
count(*):包括 NULL 值在內(nèi)的所有行。
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;