开发者

Sql query to find sum of all rows that have an identical column

This has probably been asked before but I am having no luck finding a solution. I am writing a stored procedure that needs to sum values based on another column. AMOUNT needs to be summed together where the SchoolID is equal.

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  

This is the query I have so far.

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)=@FundMonth
and R.requesttypeID = @ReqStatus                                       
and GR.grantsid 开发者_开发百科= '5' or GR.grantsid = '7'

Basically what happens is it adds all the amounts together

TOTAL
2159.45     

What I need is

TOTAL
675.97
514.72 
968.76

Is there a way to do this?


Add SchoolID (or whatever column based on which you want the totals) to the select, and add a group by for that column:

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)=@FundMonth
and R.requesttypeID = @ReqStatus                                       
and GR.grantsid = '5' or GR.grantsid = '7'
group by SchoolID


Just add a group by the identification column.


Just use a GROUP BY clause:

<your query>
GROUP BY SchoolID

This will make a separate sum for each value of SchoolID


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

What exactly are you totaling up? That is what you would group by

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜