Solved

SQL Server Sum Query

Posted on 2011-03-13
11
361 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Log size 3 20
MS SQL Server select from Sub Table 14 26
shrink table after huge delete 2 17
MS SQL + group by time 4 15
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

830 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