简体   繁体   English

SQL查询以查找具有相同列的所有行的总和

[英]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. SchoolID相等时,需要将AMOUNT加起来。

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

只需在标识列中添加一个组即可。

Just use a GROUP BY clause: 只需使用GROUP BY子句:

<your query>
GROUP BY SchoolID

This will make a separate sum for each value of SchoolID 这将为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 那就是你的分组依据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM