适用于:适用于:SQL Server 2025 (17.x) 在Microsoft Fabric 预览版中预览
Azure SQL 数据库
Azure Synapse Analytics
SQL 数据库
返回表达式中所有值的 PRODUCT 或仅返回 DISTINCT 值。 仅用于数值列。 忽略 Null 值。
Syntax
聚合函数语法。
PRODUCT ( [ ALL | DISTINCT ] expression )
分析函数语法。
PRODUCT ( [ ALL ] expression) OVER ( [ PARTITION BY clause ] ORDER BY clause)
Arguments
ALL
将聚合函数应用于所有值。 ALL 为默认值。
DISTINCT
指定 PRODUCT 返回唯一值的 PRODUCT。
expression
常量、列或函数,以及算术、按位和字符串运算符的任意组合。 表达式 是精确数值或近似数值数据类型类别的表达式,但 位 数据类型除外。 不允许聚合函数和子查询。 有关详细信息,请参阅 表达式。
OVER ([ PARTITION BY 子句 ] ORDER BY 子句 )
确定在应用函数之前行集的分区和排序。
PARTITION BY 子句将 FROM 子句生成的结果集划分为应用函数的分区。 如果未指定,则此函数将查询结果集的所有行视为单个组。
ORDER BY 子句确定执行作的逻辑顺序。 Required. 有关详细信息,请参阅 OVER 子句。
Return types
返回最精确的 表达式 数据类型中所有 表达式 值的乘积。
| Expression result | Return type |
|---|---|
| tinyint | int |
| smallint | int |
| int | int |
| bigint | bigint |
| 十进制 类别 (p, s) | 如果 (s == 0): decimal(38, 0) Else: decimal(38, 6) |
| money and smallmoney category | money |
| float 和 real category | float |
Remarks
PRODUCT 在不使用 and OVERORDER BY 子句的情况下使用时,是确定性函数。 使用 and OVER 子句指定ORDER BY时,这是不确定的。 有关详细信息,请参阅确定性函数和不确定性函数。
Examples
本文中的代码示例使用 AdventureWorks2022 或 AdventureWorksDW2022 示例数据库,可以从 Microsoft SQL Server 示例和社区项目 主页下载该数据库。
A. 将行相乘
以下示例演示如何使用 PRODUCT 函数
SELECT PRODUCT(UnitPrice) AS ProductOfPrices
FROM Purchasing.PurchaseOrderDetail
WHERE ModifiedDate <= '2002-05-24'
GROUP BY ProductId;
以下为部分结果集。
ProductOfPrices
----------
2526.2435
41.916
3251.9077
21656.2655
40703.3993
4785336.3939
11432159532.8367
5898056095.7678
B. 使用 OVER 子句
以下示例将 PRODUCT 函数与 OVER 子句一起使用,以提供假设金融工具的回报率。 数据按 finInstrument.
SELECT finInstrument,
PRODUCT(1 + rateOfReturn)
OVER (PARTITION BY finInstrument) AS CompoundedReturn
FROM (
VALUES (0.1626, 'instrumentA'),
(0.0483, 'instrumentB'),
(0.2689, 'instrumentC'),
(-0.1944, 'instrumentA'),
(0.2423, 'instrumentA'))
AS MyTable(rateOfReturn, finInstrument);
结果集如下。
finInstrument CompoundedReturn
------------- ---------------------------------------
instrumentA 1.163527
instrumentA 1.163527
instrumentA 1.163527
instrumentB 1.048300
instrumentC 1.268900