在SQL Server 2012中创建SumIf函数

时间:2022-04-14 08:48:48

I need some help building a SQL Server function that acts as a SumIf in Excel, for example

例如,我需要一些帮助构建一个SQL Server函数,该函数在Excel中充当SumIf

SumIF(Fees.Fee_Amount, Fees.Type ='Services' and Fees.Fee_Code = 'B01')

so the item that would be summed if it is a Fees.Fee_Amount and the where part is Fees.Type ='Services' and Fees.Fee_Code = 'B01'

所以,如果它是Fees.Fee_Amount,那么该项将被求和,其中where部分是Fees.Type ='Services'和Fees.Fee_Code ='B01'

Syntax would be SumIf(TableName.ColumnName, Criteria), the function would return the total.

语法将是SumIf(TableName.ColumnName,Criteria),该函数将返回总数。

1 个解决方案

#1


13  

The simplest way would be to SUM a CASE clause, like so:

最简单的方法是SUM一个CASE子句,如下所示:

SUM(CASE WHEN Fees.Type ='Services' and Fees.Fee_Code = 'B01'
         THEN Fees.Fee_Amount
    END) AS ColumnAlias,

#1


13  

The simplest way would be to SUM a CASE clause, like so:

最简单的方法是SUM一个CASE子句,如下所示:

SUM(CASE WHEN Fees.Type ='Services' and Fees.Fee_Code = 'B01'
         THEN Fees.Fee_Amount
    END) AS ColumnAlias,