Sum 函数 (Microsoft Access SQL)

适用于:Access 2013 | Access 2016

查询时返回指定字段中包含的一组值的总和。

语法

Sum(expr)

expr 占位符代表一个字符串表达式(它标识了包含您要添加的数字数据的字段),或者代表一个使用该字段中的数据执行计算的表达式。 expr 中的操作数可以包括表字段、常量或者函数(可以是固有函数或用户定义的函数,但不能是其他 SQL 聚合函数)的名称。

备注

Sum 函数计算字段值的总和。 例如,可以使用 Sum 函数来确定运货的总费用。

Sum 函数将忽略包含 Null 字段的记录。 以下示例演示如何计算 UnitPrice 和 Quantity 字段的产品总和:

SELECT 
Sum(UnitPrice * Quantity) 
AS [Total Revenue] FROM [Order Details];

在查询表达式中使用 Sum 函数。 可以将该表达式用于 QueryDef 对象的 SQL 属性中,或者在基于 SQL 查询来创建 Recordset 对象时使用该表达式。

示例

此示例使用 Orders 表计算发运到英国的订单的总销量。

此示例调用 EnumFields 过程,可以在 SELECT 语句示例中找到该过程。

Sub SumX() 
 
    Dim dbs As Database, rst As Recordset 
 
    ' Modify this line to include the path to Northwind 
    ' on your computer. 
    Set dbs = OpenDatabase("Northwind.mdb") 
 
    ' Calculate the total sales for orders shipped to 
    ' the United Kingdom. 
    Set rst = dbs.OpenRecordset("SELECT" _ 
        & " Sum(UnitPrice*Quantity)" _ 
        & " AS [Total UK Sales] FROM Orders" _ 
        & " INNER JOIN [Order Details] ON" _ 
        & " Orders.OrderID = [Order Details].OrderID" _ 
        & " WHERE (ShipCountry = 'UK');") 
 
    ' Populate the Recordset. 
    rst.MoveLast 
 
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 15 
     
    dbs.Close 
 
End Sub

另请参阅

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。