Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 123»»»

running sum cursor Expand / Collapse
Author
Message
Posted Monday, October 22, 2012 12:37 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Monday, August 19, 2013 8:08 PM
Points: 43, Visits: 566
Okay, I spent the last 24 hrs looking for a solution...I am totally new to server sql and after 24 hrs my eyes are killing me and i must ask this question which has so much help online but I still cant fix this.

Okay. here is the deal, I have this

sum column: forcount

sorry if this was answered already but after 24 hrs, my back is hurting and i am starting to get frustrated...

DECLARE RunningTotalCursor
CURSOR LOCAL FAST_FORWARD FOR
SELECT rawtrxid, forcount, emppin
FROM dbo.rawtrx
ORDER BY rawtrxid


OPEN RunningTotalCursor

DECLARE @rawtrxid INT
DECLARE @forcount int
declare @emppin int

DECLARE @RunningTotal int
SET @RunningTotal = 0

DECLARE @Results TABLE
(
rawtrxid INT NOT NULL PRIMARY KEY,
forcount int,
emppin int,
RunningTotal int
)

FETCH NEXT FROM RunningTotalCursor
INTO @rawtrxid, @forcount, @emppin

WHILE @@FETCH_STATUS = 0
BEGIN
SET @RunningTotal = @RunningTotal + @forcount

INSERT @Results
VALUES (@rawtrxid, @forcount, @emppin, @RunningTotal)

FETCH NEXT FROM RunningTotalCursor
INTO @rawtrxid, @forcount, @emppin

END

CLOSE RunningTotalCursor

DEALLOCATE RunningTotalCursor

SELECT *
FROM @Results
ORDER BY rawtrxid

the results:
rawtrxid    forcount    emppin      RunningTotal
----------- ----------- ----------- ------------
7 1 2 1
8 1 2 2
9 1 2 3
11 1 1 4
12 1 1 5
13 1 2 6

I need the running sum to restart when the employee pin changes, so it should read:

rawtrxid    forcount    emppin      RunningTotal
----------- ----------- ----------- ------------
7 1 2 1
8 1 2 2
9 1 2 3
11 1 1 1
12 1 1 2
13 1 2 1

Post #1375673
Posted Monday, October 22, 2012 12:43 PM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 10:59 AM
Points: 11,941, Visits: 10,975
The running total problem is a difficult one in sql server. A cursor is one way to do this, however it is incredibly slow for this type of thing. Take a look at this article. http://www.sqlservercentral.com/articles/T-SQL/68467/

In there it explains a process called the quirky update. It makes this type of thing a lot easier to work with. If you can't get it, You need to post ddl ( create tables scripts), sample data (insert statements) and desired output based on your sample data. Take a look at the first link in my signature for best practices when posting questions.


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1375675
Posted Monday, October 22, 2012 12:43 PM


SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Today @ 8:56 AM
Points: 4,828, Visits: 11,178
24 hours? Get some sleep!!

I think you can do this without using a cursor, but can't be sure without seeing more info about the source. Are you able to provide source DDL and sample data (corresponding with the desired results you have already posted)?




Help us to help you. For better, quicker and more-focused answers to your questions, consider following the advice in this link.

When you ask a question (and please do ask a question: "My T-SQL does not work" just doesn't cut it), please provide enough information for us to understand its context.
Post #1375676
Posted Monday, October 22, 2012 12:57 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Monday, August 19, 2013 8:08 PM
Points: 43, Visits: 566
I read that article about 100 times.

I read about 100 articles comparing different types of running sum...of which:
clr is the best way to do it but i cant get pass cursor so how am i going to do clr?
nested subqueries are too slow...and way too slow too, i have this in ms access
update query thing...i tried but for some reason I dont seem to get it....

requested data:

table: RawTrx
Columns:
RawTrxId	int	Unchecked
EmpName char(50) Checked
EmpPin numeric(18, 0) Checked
trxDate datetime Checked
trxTime datetime Checked
forkey char(50) Checked
fordelete bit Checked
forcount numeric(1, 0) Checked

checked is allow null...

rawtrxid is primary key auto number.

I tried putting a where clause but gets a syntax error each time and every place i put it.

Post #1375679
Posted Monday, October 22, 2012 1:10 PM


SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Today @ 8:56 AM
Points: 4,828, Visits: 11,178
Please help us by posting the info which Sean itemised.

If you take the time to do that, someone on this forum will post a working solution within an hour, I almost guarantee it. You are tired & we can help you if you help us with the fundamentals.



Help us to help you. For better, quicker and more-focused answers to your questions, consider following the advice in this link.

When you ask a question (and please do ask a question: "My T-SQL does not work" just doesn't cut it), please provide enough information for us to understand its context.
Post #1375689
Posted Monday, October 22, 2012 1:10 PM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 10:59 AM
Points: 11,941, Visits: 10,975
sdhanpaul (10/22/2012)
I read that article about 100 times.

I read about 100 articles comparing different types of running sum...of which:
clr is the best way to do it but i cant get pass cursor so how am i going to do clr?
nested subqueries are too slow...and way too slow too, i have this in ms access
update query thing...i tried but for some reason I dont seem to get it....

requested data:

table: RawTrx
Columns:
RawTrxId	int	Unchecked
EmpName char(50) Checked
EmpPin numeric(18, 0) Checked
trxDate datetime Checked
trxTime datetime Checked
forkey char(50) Checked
fordelete bit Checked
forcount numeric(1, 0) Checked

checked is allow null...

rawtrxid is primary key auto number.

I tried putting a where clause but gets a syntax error each time and every place i put it.



You are doing this in ACCESS???? I wouldn't begin to know how to do this in access.


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1375690
Posted Monday, October 22, 2012 1:19 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Monday, August 19, 2013 8:08 PM
Points: 43, Visits: 566
Im doing it in sql server 2005...management studio express

I used the nested subquery method in ms access before and it was slow.

You need to post ddl ( create tables scripts), sample data (insert statements) and desired output based on your sample data.


I have no idea what the ddl is.

I posted the sample results and the desired results...

I'm not sure what else I need to post...

Sorry if i seem to be hard headed...
Post #1375694
Posted Monday, October 22, 2012 1:23 PM


SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Today @ 8:56 AM
Points: 4,828, Visits: 11,178
sdhanpaul (10/22/2012)
Im doing it in sql server 2005...management studio express

I used the nested subquery method in ms access before and it was slow.

You need to post ddl ( create tables scripts), sample data (insert statements) and desired output based on your sample data.


I have no idea what the ddl is.

I posted the sample results and the desired results...

I'm not sure what else I need to post...

Sorry if i seem to be hard headed...


Have a look here for a random thread which includes DDL and INSERTs.

We need sample source data - not just the results.



Help us to help you. For better, quicker and more-focused answers to your questions, consider following the advice in this link.

When you ask a question (and please do ask a question: "My T-SQL does not work" just doesn't cut it), please provide enough information for us to understand its context.
Post #1375699
Posted Monday, October 22, 2012 1:36 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Monday, August 19, 2013 8:08 PM
Points: 43, Visits: 566
no inserts.
no ddls

sample data:

rawtrxid forcount emppin RunningTotal
----------- ----------- ----------- ------------
7 1 2 1
8 1 2 2
9 1 2 3
11 1 1 4
12 1 1 5
13 1 2 6


that is the sample data...i am running a very small database right now...the only column that is not in the sample data source is the running total.

anyways, thanks for your time.

If anyone every figures this out...i'll listen. otherwise, i going and get some sleep.

Thanks.
Post #1375701
Posted Monday, October 22, 2012 2:09 PM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 10:59 AM
Points: 11,941, Visits: 10,975
sdhanpaul (10/22/2012)
no inserts.
no ddls

sample data:

rawtrxid forcount emppin RunningTotal
----------- ----------- ----------- ------------
7 1 2 1
8 1 2 2
9 1 2 3
11 1 1 4
12 1 1 5
13 1 2 6


that is the sample data...i am running a very small database right now...the only column that is not in the sample data source is the running total.

anyways, thanks for your time.

If anyone every figures this out...i'll listen. otherwise, i going and get some sleep.

Thanks.


Yes you are tired. Go get some sleep. I think your ddl would look like this.

create table #rawtrxid
(
RawTrxID int,
ForCount int,
EmpPin int,
Total int
)

insert #rawtrxid
select 7, 1, 2, null union all
select 8, 1, 2, null union all
select 9, 1, 2, null union all
select 11, 1, 1, null union all
select 12, 1, 1, null union all
select 13, 1, 2, null

select * from #rawtrxid


See now how when we have something to work with we can make this happen? Without this there is nothing for anybody to write sql against.

So starting with that as your base, your cursor was so close. You just need a way to know what the previous EmpPin was as you process each agonizing row.

This is your modified cursor which now returns what you stated you want.

--Here is your cursor method
DECLARE RunningTotalCursor
CURSOR LOCAL FAST_FORWARD FOR
SELECT rawtrxid, forcount, emppin
FROM #rawtrxid
ORDER BY rawtrxid


OPEN RunningTotalCursor

DECLARE @rawtrxid INT
DECLARE @forcount int
declare @emppin int

DECLARE @RunningTotal int
SET @RunningTotal = 0

declare @PrevEmpPin int = -1

DECLARE @Results TABLE
(
rawtrxid INT NOT NULL PRIMARY KEY,
forcount int,
emppin int,
RunningTotal int
)

FETCH NEXT FROM RunningTotalCursor
INTO @rawtrxid, @forcount, @emppin

WHILE @@FETCH_STATUS = 0
BEGIN
if @emppin <> @PrevEmpPin
begin
Set @RunningTotal = 0
Set @PrevEmpPin = @emppin
end

SET @RunningTotal = @RunningTotal + @forcount

INSERT @Results
VALUES (@rawtrxid, @forcount, @emppin, @RunningTotal)

FETCH NEXT FROM RunningTotalCursor
INTO @rawtrxid, @forcount, @emppin

END

CLOSE RunningTotalCursor

DEALLOCATE RunningTotalCursor

SELECT *
FROM @Results
ORDER BY rawtrxid

However, we really aren't done here. This is not only incredibly wordy and hard to follow it will perform pretty poorly on even medium sized data sets. This is where quirky update comes in. Here we can produce the same result from the same source data. However, the code is only a few lines and it will perform WAY faster.

--Here is the quirky update method
declare @PrevEmpPin int
declare @RunningTotal int = 0
update #rawtrxid
set @RunningTotal = Total = case when EmpPin = @PrevEmpPin then @RunningTotal + ForCount Else ForCount End,
@PrevEmpPin = EmpPin
from #rawtrxid WITH (TABLOCKX)
OPTION (MAXDOP 1)

select * from #rawtrxid

Now of course we need to drop our temp table so we can run this again.

drop table #rawtrxid

Both the cursor and the quirky update produce the same results and they both match what you stated you want as output. Let me know if that helps.


_______________________________________________________________

Need help? Help us help you.

Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

Need to split a string? Try Jeff Moden's splitter.

Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Understanding and Using APPLY (Part 1)
Understanding and Using APPLY (Part 2)
Post #1375717
« Prev Topic | Next Topic »

Add to briefcase 123»»»

Permissions Expand / Collapse