Get SUM with GROUP BY in SQL Server

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Hi

How to get sum by Id from table

How I can get below result:

SMoney

StudYear

IdStd

3000,00

2020/21

0001A

3000,00

2020/21

0002A

1500,00

2020/21

0006A

3000,00

2020/21

0003A

My script:

declare @Cash table (Id int, SMoney money, StudYear char(7), IdStd char(5))
insert into @Cash(Id, SMoney, StudYear, IdStd)values(1, 2000, '2020/21', '0001A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(2, 3000, '2020/21', '0003A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(3, 1600, '2020/21', '0002A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(4, 1000, '2020/21', '0001A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(5, 1400, '2020/21', '0002A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(6, 1500, '2020/21', '0006A')
select * from @Cash
select IdStd, SUM(SMoney)SMoney, StudYear from @Cash group by IdStd, SMoney, StudYear

 

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi PRA,

use below query.

SQL

declare @Cash table (Id int, SMoney money, StudYear char(7), IdStd char(5))
insert into @Cash(Id, SMoney, StudYear, IdStd)values(1, 2000, '2020/21', '0001A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(2, 3000, '2020/21', '0003A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(3, 1600, '2020/21', '0002A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(4, 1000, '2020/21', '0001A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(5, 1400, '2020/21', '0002A')
insert into @Cash(Id, SMoney, StudYear, IdStd)values(6, 1500, '2020/21', '0006A')
select SUM(SMoney)SMoney, StudYear,IdStd 
from @Cash 
group by IdStd, StudYear

Output

SMoney StudYear IdStd
3000.00 2020/21 0001A
3000.00 2020/21 0002A
3000.00 2020/21 0003A
1500.00 2020/21 0006A