sum 函数的用法
SUM()
函数用于计算一组值或表达式的总和,SUM()
函数的语法如下:
SUM(DISTINCT expression)
SUM()
函数是如何工作的?
- 如果在没有返回匹配行 SELECT 语句中使用
SUM
函数,则SUM
函数返回NULL
,而不是0
。 DISTINCT
运算符允许计算集合中的不同值。SUM
函数忽略计算中的NULL
值。
SUM() 函数示例
MySQL 示例数据库模式由以下表组成:
customers
: 存储客户的数据。products
: 存储汽车的数据。productLines
: 存储产品类别数据。orders
: 存储客户订购的销售订单。orderDetails
: 存储每个销售订单的订单产品数据项。payments
: 存储客户订单的付款数据信息。employees
: 存储所有员工信息以及组织结构,例如,直接上级 (谁向谁报告工作)。offices
: 存储销售处数据,类似于各个分公司。
可以使用SUM()
函数来计算订单编号10100
的总金额,如下查询所示:
SELECT FORMAT(SUM(quantityOrdered * priceEach),2) total FROM orderdetails WHERE orderNumber = 10100;
执行上面查询语句,得到以下结果 -
mysql> SELECT FORMAT(SUM(quantityOrdered * priceEach),2) total FROM orderdetails WHERE orderNumber = 10100;
+-----------+
| total |
+-----------+
| 10,223.83 |
+-----------+
1 row in set
请注意,FORMAT()
函数用于格式化SUM()
函数的返回值。
SUM 与 GROUP BY 子句
当与GROUP BY
子句组合时,SUM()
函数计算 GROUP BY 子句中指定的每个分组的总和。
例如,可以使用具有GROUP BY
子句的SUM
函数计算每个订单的总金额,如下所示:
SELECT orderNumber,
FORMAT(SUM(quantityOrdered * priceEach),2) total
FROM orderdetails
GROUP BY orderNumber
ORDER BY SUM(quantityOrdered * priceEach) DESC;
执行上面查询语句,得到以下结果 -
+-------------+-----------+
| orderNumber | total |
+-------------+-----------+
| 10165 | 67,392.85 |
| 10287 | 61,402.00 |
| 10310 | 61,234.67 |
| 10212 | 59,830.55 |
*** 此处省略了一大波数据 *****
| 10116 | 1,627.56 |
| 10158 | 1,491.38 |
| 10144 | 1,128.20 |
| 10408 | 615.45 |
+-------------+-----------+
327 rows in set
SUM 与 HAVING
您可以使用 HAVING 子句中在SUM
函数中来根据特定条件过滤结果。例如,您可以计算总订单量,只能选择总金额大于60000
的订单。如下查询语句 -
SELECT orderNumber,
FORMAT(SUM(quantityOrdered * priceEach),2)
FROM orderdetails
GROUP BY orderNumber
HAVING SUM(quantityOrdered * priceEach) > 60000
ORDER BY SUM(quantityOrdered * priceEach);
执行上面查询语句,得到以下结果 -
mysql> SELECT orderNumber,
FORMAT(SUM(quantityOrdered * priceEach),2)
FROM orderdetails
GROUP BY orderNumber
HAVING SUM(quantityOrdered * priceEach) > 60000
ORDER BY SUM(quantityOrdered * priceEach);
+-------------+--------------------------------------------+
| orderNumber | FORMAT(SUM(quantityOrdered * priceEach),2) |
+-------------+--------------------------------------------+
| 10310 | 61,234.67 |
| 10287 | 61,402.00 |
| 10165 | 67,392.85 |
+-------------+--------------------------------------------+
3 rows in set
SUM 与 LIMIT
假设您想要计算products
表中前十名最昂贵的产品的总和,可以提出以下查询:
SELECT SUM(buyprice)
FROM products
ORDER BY buyprice DESC
LIMIT 10;
执行上面查询语句,得到以下结果 -
mysql> SELECT SUM(buyprice)
FROM products
ORDER BY buyprice DESC
LIMIT 10;
+---------------+
| SUM(buyprice) |
+---------------+
| 5983.47 |
+---------------+
1 row in set
它不起作用,因为具有SUM
函数的SELECT
语句只返回一行,LIMIT
子句约束要返回的行数无效。
要解决此问题,请使用以下子查询:
SELECT FORMAT(SUM(buyprice),2) FROM
(SELECT buyprice
FROM products
ORDER BY buyprice DESC
LIMIT 10) price;
执行上面查询语句,得到以下结果 -
+-------------------------+
| FORMAT(SUM(buyprice),2) |
+-------------------------+
| 958.71 |
+-------------------------+
1 row in set
上面语句是怎么运行的?
- 子查询选择十大价格最高的产品。
- 外部查询计算从子查询返回的前
10
个价格最高的产品的总和。
SUM 与 NULL
如果没有匹配的行,则SUM
函数返回NULL
值。 有时,您希望SUM
函数返回0
而不是NULL
。 在这种情况下,可以使用COALESCE
函数。COALESCE
函数接受两个参数,如果第一个参数为NULL
,则返回第二个参数,否则返回第一个参数; 参考以下查询语句:
SELECT COALESCE(SUM(quantityOrdered * priceEach),0)
FROM orderdetails
WHERE productCode = 'S1_212121';
执行上面查询语句,得到以下结果 -
mysql> SELECT COALESCE(SUM(quantityOrdered * priceEach),0)
FROM orderdetails
WHERE productCode = 'S1_212121';
+----------------------------------------------+
| COALESCE(SUM(quantityOrdered * priceEach),0) |
+----------------------------------------------+
| 0.00 |
+----------------------------------------------+
1 row in set
SUM 与连接语句
您可以使用 SELECT JOIN 语句中的SUM
函数根据另一个表中的值指定的条件来计算表中的值的总和。
例如,要计算取消订单金额的总和,请使用以下语句:
SELECT FORMAT(SUM(quantityOrdered * priceEach),2) loss
FROM orderdetails
INNER JOIN orders USING(orderNumber)
WHERE status = 'Cancelled'
SUM(布尔表达式)
创建表
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
`日期` date NULL DEFAULT NULL,
`结果` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
插入数据
INSERT INTO `a` VALUES ('2015-05-09', '胜');
INSERT INTO `a` VALUES ('2015-05-09', '胜');
INSERT INTO `a` VALUES ('2015-05-09', '负');
INSERT INTO `a` VALUES ('2015-05-09', '负');
INSERT INTO `a` VALUES ('2015-05-10', '胜');
INSERT INTO `a` VALUES ('2015-05-10', '负');
INSERT INTO `a` VALUES ('2015-05-10', '负');
查询
select 日期,sum(结果='胜') as 胜,sum(结果='负') as 负 from a group by 日期;
SUM(if 条件)
select source.to_els_account as elsAccount ,sum(if(source.performance_deduce=0 and source.grade='III',source.fbk2,0))as significantQualityLevelThreeScore,
sum(if(source.performance_deduce=0 and source.grade='II',source.fbk2,0))as significantQualityLevelTwoScore,sum(if(source.performance_deduce=0 and source.grade='I',source.fbk2,0))as significantQualityLevelOneScore,
sum(source.performance_deduce=0 and source.grade='III')as significantQualityLevelThreeNum,
sum(source.performance_deduce=0 and source.grade='II')as significantQualityLevelTwoNum,sum(source.performance_deduce=0 and source.grade='I')as significantQualityLevelOneNum,
DATE_FORMAT(source.oa_syn_date,'%Y-%m') as supplierPerformanceSourceDate,
info.org_name as companyName,info.org_code as company
FROM purchase_material_major_quality_fault_source source,purchase_organization_info info
where 1=1
and info.org_code=source.company and info.org_category_code='companyCode'
and source.oa_syn_date between #{startTime} and #{endTime}
group by source.to_els_account,company,supplierPerformanceSourceDate