Solved

SQL Server Sum Query

Posted on 2011-03-13
11
357 Views
Last Modified: 2012-05-11
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
Comment
Question by:TaibaDXB
  • 4
  • 3
  • 2
  • +2
11 Comments
 
LVL 15

Expert Comment

by:Aaron Shilo
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

by:TaibaDXB
ID: 35121559
Thank you for your reply.
I need it in a "Select" statement as I can't create tables for that.
0
 
LVL 11

Expert Comment

by:JoeNuvo
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

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

Open in new window

0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35121589
sorry corrected:-

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

Open in new window

0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:TaibaDXB
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

by:mayank_joshi
ID: 35121639
0
 
LVL 11

Accepted Solution

by:
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

Open in new window



0
 
LVL 75

Expert Comment

by:Anthony Perkins
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

by:mayank_joshi
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

by:TaibaDXB
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

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Join & Write a Comment

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.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now