如何在由where子句过滤后对列进行求和

时间:2013-07-12 14:44:11

标签: sql sql-server

我试图在使用where子句过滤后对查询结果求和。但是,当我尝试时,它会将整个列数相加,而不考虑过滤后的结果。这是我正在使用的当前代码:

FROM [MBS_STATS].[dbo].[Performance_2012Q2]



  Where dbo.Performance_2012Q2.[Current Interest Rate] >= 3.00 AND dbo.Performance_2012Q2.[Current Interest Rate] < 3.10 and dbo.Performance_2012Q2.[Monthly Reporting Period] = '03/01/2013'


Select SUM (Convert (float,(dbo.Performance_2012Q2.[Current Actual Unpaid Principal Balance]))) from dbo.Performance_2012Q2 

有谁能告诉我如何对where子句产生的查询结果求和?谢谢!

我正在使用SQL Server 2012

2 个答案:

答案 0 :(得分:2)

你似乎正在遭受对SQL如何工作的根本误解。您需要在单个查询中聚合和过滤

Select SUM (Convert (float,(dbo.Performance_2012Q2.[Current Actual Unpaid Principal   Balance]))) from dbo.Performance_2012Q2
Where dbo.Performance_2012Q2.[Current Interest Rate] >= 3.00 AND dbo.Performance_2012Q2.[Current Interest Rate] < 3.10 and dbo.Performance_2012Q2.[Monthly Reporting Period] = '03/01/2013'

答案 1 :(得分:2)

您仍然以标准方式编写查询:

Select SUM (Convert (float,(dbo.Performance_2012Q2.[Current Actual Unpaid Principal Balance])))
from dbo.Performance_2012Q2 
Where dbo.Performance_2012Q2.[Current Interest Rate] >= 3.00
And dbo.Performance_2012Q2.[Current Interest Rate] < 3.10
And dbo.Performance_2012Q2.[Monthly Reporting Period] = '03/01/2013'

数据库引擎将首先应用您的WHERE子句,然后汇总结果。