在 SQL Server 2012 中创建 SumIf 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30242862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:37:04  来源:igfitidea点击:

Creating SumIf function in SQL Server 2012

sqlsql-server

提问by Bill

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

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

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_Amountand the where part is Fees.Type ='Services'and Fees.Fee_Code = 'B01'

所以如果它是 aFees.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),该函数将返回总数。

回答by

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,