Solved

SQL Server Sum Query

Posted on 2011-03-13
11
358 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

863 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

25 Experts available now in Live!

Get 1:1 Help Now