I have a table defined in the below code, I expect to have a sum of all values as ALLDays, in this case for Ajan 36 and for Sam 21. How can I modify the below query to get that, I'm not allowed to use windows function.I can achieve the requirment by having another query grouped by student and join both but is there any way to modify the below query to cater the requirement. any help is much appreciated.
DECLARE @Table
TABLE(Student varchar(50),
subject varchar(50)
,days int)
Insert into @Table
values('Ajan','English',8),('Ajan','Math',9),('Ajan','Science',7),('Ajan','English',5),('Ajan','Math',4),('Ajan','Science',3),
('Sam','English',7),('Sam','Math',6),('Sam','Science',8)
select student,subject,sum(days) as SubjectDays,'' as AllDays from @Table
group by student,subject
If you can't use window functions, then one alternative would be to use two separate subqueries for the student and subject level sums of days.
select t1.student, t1.subject, t1.SubjectDays, t2.AllDays
from
(
select student, subject, sum(days) as SubjectDays
from @Table
group by student, subject
) t1
inner join
(
select student, sum(days) as AllDays
from @Table
group by student
) t2
on t1.student = t2.student;