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

时间:2011-08-02 17:40:26

标签: sql sql-server

之前可能已经提出这个问题,但我找不到解决方案。我正在编写一个存储过程,需要根据另一列对值进行求和。在AMOUNT相等的情况下,SchoolID需要汇总在一起。

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

基本上会发生什么,它会将所有金额加在一起

TOTAL
2159.45     

我需要的是

TOTAL
675.97
514.72 
968.76

有办法做到这一点吗?

4 个答案:

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

答案 1 :(得分:1)

只需在标识栏中添加一个组。

答案 2 :(得分:1)

只需使用GROUP BY子句:

<your query>
GROUP BY SchoolID

这将为SchoolID

的每个值单独计算一笔

答案 3 :(得分:0)

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

你到底在做什么?这就是你要分组的内容