July 24, 2005 at 9:24 pm
Assuming I have a table with the just the fields "MemberNo" and "ClaimCount", for example "ABC123" "2", where there are multiple records having the same MemberNo with a different ClaimCount, how could I create a third column, say, "Running Total" in a Query, which would keep a cumulative running count of the ClaimCount value for each MemberNo.?
Example:
MemberNo ClaimCount RunningTot
'ABC123' 1 1
'ABC123' 2 3
'ABC123' 1 4
Thanks.
July 25, 2005 at 12:56 am
You need to be able to sort the rows in your table in some way such that you can tell where to begin and where to end your calculation (in other words, referring to your example, which row should have a RunningTot of 4?). Do you have a unique id on your table?
July 26, 2005 at 12:30 am
Try this:
if exists (select * from dbo.sysobjects
where id = object_id(N'Test')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table Test
GO
CREATE TABLE Test (MemberNo varchar(6)
, ClaimCount int
, RunningTot int)
GO
INSERT INTO Test (MemberNo,ClaimCount)
VALUES ('ABC123',1)
INSERT INTO Test (MemberNo,ClaimCount)
VALUES ('ABC123',2)
INSERT INTO Test (MemberNo,ClaimCount)
VALUES ('ABC123',1)
GO
DECLARE @RunningTot int
SET @RunningTot = 0
UPDATE Test
SET @RunningTot = RunningTot = @RunningTot + ClaimCount
GO
SELECT * FROM Test
GO
Andy
July 26, 2005 at 1:13 am
Very nice.... learned a new trick there (column RunningTot should be nullable in order for your example to run).
July 26, 2005 at 1:31 am
A well known trick is this: http://www.sqlteam.com/item.asp?ItemID=765
The major drawback here is that you can't control the order in which the rows are updated. There is no guarantee that they are updated in the order you want them to.
Anyway, you should really change the underlying table structure and add at least a PRIMARY KEY. The way your structure looks like now, the data is kinda meaningless.
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
July 26, 2005 at 1:48 am
Thanks, Frank... Although this is a very nice trick that might be useful in some situations, I agree with your remarks.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply