在 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
Creating SumIf function in SQL Server 2012
提问by Bill
I need some help building a SQL Server function that acts as a SumIf
in 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_Amount
and 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,