如何在 SQL 服务器中计算聚合产品函数

How to Calculate Aggregated Product Function in SQL Server

我有一个 table 有 2 列:

No.  Name    Serial
1    Tom       1
2    Bob       5
3    Don       3
4    Jim       6

我想添加一个列,其内容是 multiply Serial 列,如下所示:

No.  Name    Serial   Multiply
1    Tom       2         2
2    Bob       5         10
3    Don       3         30
4    Jim       6         180

我该怎么做?

哦,这很痛苦。大多数数据库不支持 product 聚合函数。您可以使用日志和权力来模拟它。所以,这样的事情可能会奏效:

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

请注意,log() 在某些数据库中可能被称为 ln()。此外,这适用于 positive 数字。有处理负数和零的变体,但这会使答案复杂化(样本数据都是正数)。

创建 CLR 聚合还不错。我在大约 5 分钟内搞定了这个:

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.Native)]
public struct Product
{
    private SqlDouble _p;
    public void Init()
    {
        this._p = new SqlDouble(1);
    }

    public void Accumulate(SqlDouble Value)
    {
        this._p *= Value;
    }

    public void Merge (Product Group)
    {
        this._p *= Group._p;
    }

    public SqlDouble Terminate ()
    {
        // Put your code here
        return _p;
    }
}

一旦你明白了,你可以使用通常用于 运行 总和的技术(即三角连接或 window 界定行的定义,这取决于你的版本sql).