0

在使用 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

4

2 回答 2

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'
于 2013-07-12T14:47:11.617 回答
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 子句,然后聚合结果。

于 2013-07-12T14:47:53.480 回答