之前可能已经提出这个问题,但我找不到解决方案。我正在编写一个存储过程,需要根据另一列对值进行求和。在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
有办法做到这一点吗?
答案 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 ?
你到底在做什么?这就是你要分组的内容