Solved

# SQL Server Sum Query

Posted on 2011-03-13
357 Views
Hi.
I have a table similar to this:
Orders
======
OrderID            TotalWeight
======            ==========
1                           100
2                           150
3                           400
.
.
.
I need to get this output:
OrderID          TotalWeight            TempTotalWeight
======         ==========            ==============
1                         100                               100    ( 0 + 100 )
2                         150                               250    ( 100 + 150 )
3                         400                               650    ( 100 + 150 + 400 )

How to write the sql statement for it with the best performance ( I have a lot of Data )?
0
• 4
• 3
• 2
• +2

LVL 15

Expert Comment

ID: 35121554
create a reference table

reftable (totalweight int , temptotalweight varchar(50))

insert into reftable values(100, '100 (0+100))
insert into reftable values(150, '250 (100+150))
...

0

Author Comment

ID: 35121559
I need it in a "Select" statement as I can't create tables for that.
0

LVL 11

Expert Comment

ID: 35121570
the simple one is this, but I will try to see if can have something better (for performance)

SELECT
OrderID,
TotalWeight,
(SELECT SUM(TotalWeight) FROM Orders B WHERE B.OrderID <= A.OrderID) TempTotalWeight
FROM Orders A
ORDER BY OrderID
0

LVL 9

Expert Comment

ID: 35121585
``````select OrderId, O.TotalWeight ,(select sum(TotalWeight) from Orders where OrderID <= O.OrderID) ''Running TotalWeight' from Orders O
``````
0

LVL 9

Expert Comment

ID: 35121589
sorry corrected:-

``````select OrderId, O.TotalWeight ,(select sum(TotalWeight) from Orders where OrderID <= O.OrderID) 'Running TotalWeight' from Orders O
``````
0

Author Comment

ID: 35121599
I have tested this query against my table, it works but its performance is bad :(
I have now around 13000 rows in the table & it took around 39 sec to complete the query!!
I am looking for faster select statement.
Any other suggestions?
0

LVL 9

Expert Comment

ID: 35121639
0

LVL 11

Accepted Solution

JoeNuvo earned 400 total points
ID: 35121655
If it's ok to have multiple command
here is my new code.

``````Declare @temp TABLE (OrderID int PRIMARY KEY, TotalWeight int, TempTotalWeight bigint)

INSERT INTO @temp
SELECT OrderID, TotalWeight, 0
FROM Orders
ORDER BY OrderID

Declare @sum BigInt
SET @sum = 0

UPDATE @temp
SET
@sum = @sum + TotalWeight,
TempTotalWeight = @sum

SELECT * FROM @temp
``````

0

LVL 75

Expert Comment

ID: 35122036
>>I have tested this query against my table, it works but its performance is bad <<
Not surprising.  Typically the presentation layer handles running totals and not SQL Server.  You may get slightly better performance using a CTE, but I would not hold you breath.  Simply put, this is a bad idea.
0

LVL 9

Assisted Solution

mayank_joshi earned 100 total points
ID: 35125520
computed column can give you good performance for running total:-

http://davidfrommer.blogspot.com/2008/08/using-computed-column-to-calculate.html
0

Author Comment

ID: 35125993
Thank you all for suggestions.
Using the temp table gave me great results & also using the Self join query from this post http://davidfrommer.blogspot.com/2008/08/using-computed-column-to-calculate.html
but the temp table was better.
0

## Featured Post

### Suggested Solutions

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.