MariaDB SUM()
函數(shù)用于返回表達(dá)式求和的值。
語法:
SELECT SUM(aggregate_expression)
FROM tables
[WHERE conditions];
數(shù)據(jù)準(zhǔn)備
在"testdb"
數(shù)據(jù)庫中創(chuàng)建一個(gè)"students"
表,并插入一些數(shù)據(jù)。參考以下創(chuàng)建語句 -
USE testdb;
DROP TABLE students;
-- 創(chuàng)建新表
CREATE TABLE students(
student_id INT NOT NULL AUTO_INCREMENT,
student_name VARCHAR(100) NOT NULL,
student_address VARCHAR(40) default NULL,
admission_date DATE,
score float(4, 1) default NULL,
PRIMARY KEY ( student_id )
);
-- 插入數(shù)據(jù)
INSERT INTO students
(student_id, student_name, student_address,score, admission_date)
VALUES(1,'Maxsu','Haikou', 99.5,'2017-01-07 00:00:00');
INSERT INTO students
(student_id, student_name, student_address, score, admission_date)
VALUES
(2,'Crurry','Beijing',86,'2016-05-07 00:00:00'),
(3,'JMaster','Beijing',91,'2016-05-07 00:00:00'),
(4,'Mahesh','Guangzhou',78,'2016-06-07 00:00:00'),
(5,'Kobe','Shanghai',89,'2016-02-07 00:00:00'),
(6,'Blaba','Shengzhen',100,'2016-08-07 00:00:00');
示例:
計(jì)算student_id
大于1
的Student
表的總分?jǐn)?shù)。參考以下查詢語句 -
SELECT SUM(Score) AS "Total Score"
FROM students
WHERE student_id > 1;
執(zhí)行上面查詢語句,得到以下結(jié)果 -
MariaDB [testdb]> SELECT SUM(Score) AS "Total Score"
-> FROM students
-> WHERE student_id > 1;
+-------------+
| Total Score |
+-------------+
| 444.0 |
+-------------+
1 row in set (0.00 sec)
可以使用SUM
函數(shù)的DISTINCT
子句來避免重復(fù)值的總和。
再插入一條重復(fù)的數(shù)據(jù) -
INSERT INTO students
(student_name, student_address,score, admission_date)
VALUES('Maxsu','Haikou', 99.5,'2017-11-07 00:00:00');
當(dāng)前數(shù)據(jù)庫中的記錄如下 -
MariaDB [testdb]> select * from students;
+------------+--------------+-----------------+----------------+-------+
| student_id | student_name | student_address | admission_date | score |
+------------+--------------+-----------------+----------------+-------+
| 1 | Maxsu | Haikou | 2017-01-07 | 99.5 |
| 2 | Crurry | Beijing | 2016-05-07 | 86.0 |
| 3 | JMaster | Beijing | 2016-05-07 | 91.0 |
| 4 | Mahesh | Guangzhou | 2016-06-07 | 78.0 |
| 5 | Kobe | Shanghai | 2016-02-07 | 89.0 |
| 6 | Blaba | Shengzhen | 2016-08-07 | 100.0 |
| 7 | Maxsu | Haikou | 2017-11-07 | 99.5 |
+------------+--------------+-----------------+----------------+-------+
7 rows in set (0.00 sec)
示例:
SELECT SUM(DISTINCT Score) AS "Total Score"
FROM students
WHERE student_name = 'Maxsu';
執(zhí)行上面查詢語句,得到以下結(jié)果 -
MariaDB [testdb]> SELECT SUM(DISTINCT Score) AS "Total Score"
-> FROM students
-> WHERE student_name = 'Maxsu';
+-------------+
| Total Score |
+-------------+
| 99.5 |
+-------------+
1 row in set (0.00 sec)