SQLite AVG() 函数
SQLite AVG()
函数用于计算某列的平均值
SELECT avg(fieldname) FROM tablename;
先运行下面的 SQLite SQL 语句创建测试数据
DROP TABLE tbl_employee; CREATE TABLE tbl_employee ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name CHAR(64) NOT NULL, age INTEGER NOT NULL, city CHAR(64), salary REAL ); INSERT INTO tbl_employee (name,age,city,salary) VALUES ('张三', 25, 'pek', 102400.00 ), ('李四', 18, 'shanghai', 88888.00 ), ('王五', 22, 'hangzhou', 22000.00 ), ('孙六', 32, 'pek', 32000.00 ), ('钱七', 25, 'shanghai', 25000.00 ), ('赵二', 45, 'pek', 45800.00 ), ('冯九', 37, 'chengdu', 15000.00 );
然后运行下面的 SQLite 语句计算 tbl_employee
表 salary
的平均值
SELECT avg(salary) FROM tbl_employee;
输出结果如下
avg(salary) ---------------- 47298.2857142857
可以把 fieldname
替换成任何表达式
SELECT avg(salary/age) FROM tbl_employee;
输出结果如下
avg(salary/age) ---------------- 1922.48648648649
如果要计算城市薪水的平均值,那么就要使用 GROUP BY 语句了
SELECT city,avg(salary) FROM tbl_employee GROUP BY city;
输出结果如下
city avg(salary) ---------- ----------- chengdu 15000.0 hangzhou 22000.0 pek 60066.66666 shanghai 56944.0