2011-08-02 51 views
1

這可能以前已經問過,但我沒有找到解決方案的運氣。我正在編寫一個存儲過程,需要根據另一列對值進行求和。當SchoolID相等時,需要將AMOUNT相加在一起。SQL查詢找到具有相同列的所有行的總和

ID  ReqID SchoolID NAME   AMOUNT 
141  30  0104  LaborHilto 148.72 
142  30  0104  LabClaxton 242.25 
143  30  0104  LabWilliam 285.00 
144  30  0196  LabWilliam 249.00 
151  30  0196  Kelly  265.72 
163  30  2056  Kelley  968.76 

這是我到目前爲止的查詢。

select distinct sum(i.amount) 
from invoice i inner join vSchool v on v.SchoolID = i.SchoolID and v.SystemID = @SystemID 
inner join request R on R.requestid = i.requestid 
inner join grantsystem G on G.grantsystemID = R.grantsystemID 
inner join grants GR on GR.grantsid = G.grantsID 
where i.SchoolID = v.SchoolID           
and i.ReimbursementTypeID = '29'    
and month(R.FundMonth)[email protected] 
and R.requesttypeID = @ReqStatus          
and GR.grantsid = '5' or GR.grantsid = '7' 

基本上會發生什麼是它增加了所有的貨款一起

TOTAL 
2159.45  

我需要的是

TOTAL 
675.97 
514.72 
968.76 

有沒有辦法做到這一點?

+2

你試過Group By? –

+0

什麼版本的SQL Server? – Lucero

+0

使用羣組,這將允許您基於您的位置來總結i.amount。 Group By i.amount –

回答

1

只需通過標識欄添加一個組。

0
Select amount as [Total] 
From [whatever tables etc..] 
Group by ReqID ? 

究竟是什麼總數?那是你會被

+0

'GROUP BY SchoolID',可能。 –

1

組只需使用一個GROUP BY條款:

<your query> 
GROUP BY SchoolID 

這將使一個單獨的總和的SchoolID每個值

4

添加SchoolID(或任何基於列的要在其上總計),併爲該列添加group by

select SchoolID, sum(i.amount) 
from invoice i inner join vSchool v on v.SchoolID = i.SchoolID and v.SystemID = @SystemID 
inner join request R on R.requestid = i.requestid 
inner join grantsystem G on G.grantsystemID = R.grantsystemID 
inner join grants GR on GR.grantsid = G.grantsID 
where i.SchoolID = v.SchoolID           
and i.ReimbursementTypeID = '29'    
and month(R.FundMonth)[email protected] 
and R.requesttypeID = @ReqStatus          
and GR.grantsid = '5' or GR.grantsid = '7' 
group by SchoolID 
相關問題