在本教程中,我们将学习如何使用SQL SUM函数计算所有值或不同值的和。
SUM函数返回数字和。它的语法如下:
SUM
(
DISTINCT
|
ALL
数字表达式)
与其他SQL聚合函数不同,SUM()函数只接受计算后为数值的表达式。
你可以在SUM函数中指定ALL或DISTINCT修饰符。其中:
要获得库存数量和订购数量的总和,可以使用SUM()函数,如下所示:
SELECT
(unitsinstock),
(unitsonOrder)
FROM
products;
要获取每个供应商库存数量的总和,可以将SUM()函数与GROUP BY子句一起使用:
supplierid,
(unitsinstock)
products
GROUP
BY
supplierid;
GROUP BY子句将按供应商对产品进行分组。对于每个组,SUM()函数计算库存数量的和。
要获取库存单位总数小于50的供应商,需要将sum()函数与GROUP by和HAVING子句一起使用,如下所示:
supplierid
HAVING
(unitsinstock) < 50;
我们可以对SUM表达式使用别名,下面的语句作用是一样的:
(unitsinstock) totalinstock
totalinstock < 50;
我们还可以使用SUM函数处理更具挑战性的业务问题,比如按销售额获取前5名客户,如下所示:
customers.customerid,
companyname,
(unitprice * quantity) -
(unitprice * quantity) * discount)
AS
total
orderdetails
INNER
JOIN
orders_test
ON
orders_test.orderid = orderdetails.orderid
customers
customers.customerid = orders_test.customerid
customers.customerid
ORDER
DESC
LIMIT 5
下面的查询使用SUM()函数得到5个最畅销的产品:
p.productid,
p.productname,
(o.unitprice * quantity) -
(o.unitprice * quantity) * discount) total
orderdetails o
products p
p.productid = o.productid
p.productid
LIMIT 5;
原文链接:https://codingdict.com/