-- 創建員工表 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;