SQLTeam.com | Weblogs | Forums

SQL SUM Query Help


#1

Hello all,

Below are my sql query and the result set:

SELECT YR_MTH, Total_Part
FROM Part_Tbl

result set:
03

The result I need to achieve:
04

So, basically, record # 1 add to # 2, then the sum will add to # 3, the sum of that will add to # 4 and so on.

How do I achieve this? Anyone?

Thank you all


#2

What version of SQL are you on? SQL 2005 / 2008 / 2012+? The answer can vary based on version.


#3

I am using SQL 2012. Thanks ScottPletcher.


#4

That's great, you can use the "new" (as of SQL 2012) and easy approach. I don't have useable sample data to test it with, but something like this should work:

SELECT
    Yr_Mnt, Part, 
    SUM(Part) OVER(ORDER BY Yr_Mnt ROWS UNBOUNDED PRECEDING) AS Total
FROM dbo.Part_Tbl
ORDER BY Yr_Mnt

#5

Thank you ScottPletcher