且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL Server中计算聚合产品函数

更新时间:2022-06-08 09:53:25

哦,这是痛。大多数数据库不支持产品聚合功能。您可以使用日志和功能来模拟它。因此,这样的操作可能会起作用:

Oh, this is a pain. Most databases do not support a product aggregation function. You can emulate it with logs and powers. So, something like this might work:

select t.*,
       (select exp(sum(log(serial)))
        from table t2
        where t2.no <= t.no
       ) as cumeProduct
from table t;

请注意,可能会调用 log()在某些数据库中 ln()。同样,这适用于数字。有多种处理负数和零的方法,但这会使答案复杂化(示例数据都是正数)。

Note that log() might be called ln() in some databases. Also, this works for positive numbers. There are variations to handle negative numbers and zeroes, but this complicates the answer (and the sample data is all positive).