Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 running totals on calculated columns

Author  Topic 

spadeyboy
Starting Member

1 Post

Posted - 2011-10-19 : 23:46:06
Hi Everyone,

Hi I currently have 6 columns in my database that are counters(from a flow meter counting liters / min). I need to take that column and get the difference from the previous value and make that its own column. then i need to take that column and make a running total column for it. I cannot write to the database.

ID counter counterdif counterdifsum
1 387 0 0
2 387 0 0
3 389 2 2
4 392 3 5
5 396 4 9
6 396 0 9

Thats my desired output. I have tried and succeeded in making that entire process for just one of the counters in a query but it takes forever. 1 minute to return 200 rows. it will need to return 40,000 total :(

Hoping someone might be able to point me in the right direction :)
code i am using below (sorry its terrible lol)
Thanks!

WITH    rows AS 
(
SELECT no1aliquidcounter,
ROW_NUMBER() OVER (ORDER BY ID) AS rn,
ID
FROM datatable
WHERE ringnum = 120
) ,
M as
(

SELECT
(mp.no1aliquidcounter - mc.no1aliquidcounter) /1000 AS no1aliquidcountdiff,
mc.ID

FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn - 1

),
RUNNER(
ID,
no1aliquidcountdiff,
no1aliquidcountdiffttl)
AS
(
SELECT
a.ID,
a.no1aliquidcountdiff,
(SELECT
SUM(b.no1aliquidcountdiff)
FROM M AS b
WHERE b.ID <= a.ID)
FROM M AS a
)
SELECT * FROM RUNNER

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-20 : 00:17:20
why are you using subquery?
try using APPLY instead as in below

http://visakhm.blogspot.com/2010/01/multipurpose-apply-operator.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -