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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Any option wihout using cursors???

Author  Topic 

sahu74
Posting Yak Master

100 Posts

Posted - 2005-10-10 : 17:45:38
I have the following records in table ABC.

UserID Points

9179 3.00
9179 15.84
6838 7.92
6838 31.68
6326 19.80
9530 15.84
5033 7.92
8670 0.20
8670 4.62
8670 3.18

For each UserID I would like to accumulate a maximum of 6.00 points in the 'Points Used' and carry over the rest into the 'Balance' column.

ID Points Accumulated Balance
Used Points

9179 3.00 3.00 0.00
9179 3.00 6.00 12.84
6838 6.00 6.00 1.92
6838 0.00 6.00 33.60
6326 6.00 6.00 13.80
9530 6.00 6.00 9.84
5033 6.00 6.00 1.92
8670 0.20 0.20 0.00
8670 4.62 4.82 0.00
8670 1.18 6.00 2.00

I thought of using cursors but thought there should be a way to do this without using cursors.

Any suggestions will be appreciated.
Thank you.
PKS.


nathans
Aged Yak Warrior

938 Posts

Posted - 2005-10-10 : 18:27:20
Have a look at this setup. I am using some of the techniques from this sqlteam article: [url]http://www.sqlteam.com/item.asp?ItemID=3856[/url]

I added a datetime stamp to each point trans in @abc.


set nocount on

declare @abc table (userID int, points decimal(10,2), dt datetime)
insert into @abc
select 9179, '3.00', getdate()- 0 union
select 9179, '15.84', getdate()- 1 union
select 6838, '7.92', getdate()- 2 union
select 6838, '31.68', getdate()- 3 union
select 6326, '19.80', getdate()- 4 union
select 9530, '15.84', getdate()- 5 union
select 5033, '7.92', getdate()- 6 union
select 8670, '0.20', getdate()- 7 union
select 8670, '4.62', getdate()- 8 union
select 8670, '3.18', getdate()- 9


select d.userID,
d.total as 'points_used',
case
when d.running_total < '6.00' then running_total
else '6.00'
end as 'accumulated_points',
case
when d.running_total < '6.00' then 0
else d.running_total - '6.00'
end as 'balance'
from (
SELECT a.userID,
a.points as 'total',
SUM(b.points) as 'running_total',
a.dt
FROM @abc a
CROSS JOIN @abc b
WHERE (a.dt <= b.dt and a.userID = b.userID)
GROUP BY a.userID,a.points, a.dt) d
order by d.dt desc


Nathan Skerl
Go to Top of Page

sahu74
Posting Yak Master

100 Posts

Posted - 2005-10-11 : 12:01:18
Nathan,
Thank you so much. This works perfect. I always knew there's way to work without using cursors.

Appreciate your help.

PKS.
Go to Top of Page

nathans
Aged Yak Warrior

938 Posts

Posted - 2005-10-12 : 16:19:06
No problem. Im glad to see you resisting the dark side.


Nathan Skerl
Go to Top of Page
   

- Advertisement -