SQLite SUM() 函数
SQLite SUM()
函数用于计算一个数值列的总和
SELECT sum(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 sum(salary) FROM tbl_employee;
输出结果如下
sum(salary) ----------- 331088.0
可以把 fieldname
替换成任何表达式
SELECT sum(salary/age) FROM tbl_employee;
输出结果如下
sum(salary/age) ---------------- 13457.4054054054
如果要计算城市薪水的总和,那么就要使用 GROUP BY 语句了
SELECT city,sum(salary) FROM tbl_employee GROUP BY city;
输出结果如下
city sum(salary) ---------- ----------- chengdu 15000.0 hangzhou 22000.0 pek 180200.0 shanghai 113888.0