Solved

SQL Server Sum Query

Posted on 2011-03-13
11
365 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 
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
 

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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

627 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