Creating Sumif Function in Sql Server 2012

Creating Sumif Function in Sql Server 2012

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

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'

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

1 Answer

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.