Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (6.1k points)
edited by

I have tried to find the whole sum of a column in the SQL Server 2008 R2 after sorting the column in the ascending order. I can't use the rows unbounded preceding or following as it is just available for the SQL Server 2012 and new versions. 

I used the below code :

    sum (Total_marks) over (order by Total_marks ASC) as cumulative_Total  
from table

But I am getting the following error:

Incorrect syntax near 'order'

How can I resolve this?

1 Answer

0 votes
by (12.7k points)
edited by

One choice which does not use a window function would be to use a correlated subquery to calculate the running total:

    (select sum(Total_marks) from table t2
     where t2.Total_marks <= t1.Total_marks) as cumulative_Total
from table t1
order by t1.Total_marks

This implies that you actually need to order the running total using the thing you are attempting to sum, namely the Total_marks. In general, you could use the below-correlated subquery if you plan to use a different column for ordering:

(select sum(Total_marks) from table t2
where t2.some_col <= t1.some_col) as cumulative_Total

Want to Learn SQL to get expertise in the concepts of SQL? Join the SQL course and get certified after clearing SQL certification exam.

Related questions

Browse Categories