在 SQL 中,聚合函数 SUM() 可以与 GROUP BY 子句一起使用,根据一个或多个列计算行的分组总和。
示例
-- calculate the total amount spent by each customer
SELECT customer_id, SUM(amount) AS total_amount_spent
FROM Orders
GROUP BY customer_id;
在这里,SQL 命令计算每个客户的总花费金额。
SQL SUM() 结合 GROUP BY
考虑之前的查询,我们计算每个客户的总花费金额。
-- calculate the total amount spent by each customer
SELECT customer_id, SUM(amount) AS total_amount_spent
FROM Orders
GROUP BY customer_id;
在这里,SUM()
函数用于聚合 amount 列。结果按 customer_id 列分组,得出每个客户的总花费金额。
在这里,结果集包含一个名为 total_amount_spent 的列,这是为 SUM()
函数结果指定的 别名。
SUM() 结合 GROUP BY 和 JOIN
我们可以通过 JOIN
操作将两个表合并,然后对结果进行分组来获得总和。
让我们看一个例子。
-- calculate the total amount spent by customers in each country
SELECT c.country, SUM(o.amount) AS total_amount_spent
FROM Customers c
JOIN Orders o ON c.customer_id = o.customer_id
GROUP BY c.country;
在这里,SQL 命令通过在 customer_id
上连接 Customers 和 Orders 表来计算客户支出,并按 country
对结果进行分组。
访问 SQL JOIN 了解更多关于 SQL 中 JOIN
子句的信息。
SUM() 结合 GROUP BY 和 HAVING
我们可以将 SUM()
函数与 GROUP BY
一起使用,并应用 HAVING 子句根据聚合函数过滤结果集。例如,
-- retrieve total order amount and filter with HAVING
SELECT customer_id, SUM(amount) AS total_order_amount
FROM Orders
GROUP BY customer_id
HAVING SUM(amount) > 500;
在这里,SQL 命令计算了所有下过订单的客户的总订单金额。
它还过滤了结果,只包含那些花费超过 **500** 的客户。