Help with avoiding CURSOR for Column Calculation
I have a bunch of records in a table variable like so:
Id ProductId Rank RankCreated
1 123213 2 2011-05-02
2 123213 4 2011-05-03
3 123213 1 2011-05-03
4 155432 10 2011-05-01
5 155432 10 2011-05-02
Id is an identity column i added to my table variable (will explain why i need it in a moment). ProductId is a Product. Rank is a value which represents a product's rank at a given time. RankCreated is the time that Product was ranked.
What im trying to do:
Calculate the "movement" between each product rank, for each product. Where "movement" is defined as current - previous.
So the "computed column" would look like this:
Id ProductId Rank RankCreated Movement
1 123213 2 2011-05-02 NULL
2 123213 4 2011-05-03 2
3 123213 1 2011-05-03 -3
4 155432 10 2011-05-01 NULL
5 155432 10 2011-05-02 0
I added the Id column so i could use that to fetch the previous record.
Here's how i got the data into the temp table:
insert into @rankhistories (productid, [rank], [rankcreated])
select a.ProductId, b.[rank]
from dbo.ProductRankHistories b
in开发者_如何学Pythonner join dbo.Products a on a.ProductId = b.ProductId
order by a.ProductId, b.RankCreated
I really can't see how i can avoid a cursor here. There are 6000+ records in that table variable, and with my cursor solution it took 5 seconds, which isn't acceptable.
Can anyone help?
DECLARE @TV TABLE
(
Id INT IDENTITY(1,1) PRIMARY KEY,
ProductId INT,
Rank INT,
RankCreated DATE
)
/*Populate *6000 rows of random data*/
INSERT INTO @TV
SELECT TOP 6000
ROW_NUMBER() OVER (ORDER BY (SELECT 0)) / 9 AS ProductId,
CRYPT_GEN_RANDOM(1) % 10 AS Rank,
GETDATE() AS RankCreated
FROM master..spt_values v1,master..spt_values v2
SELECT t1.Id,
t1.ProductId,
t1.Rank,
t1.RankCreated,
t2.Rank - t1.Rank AS Movement
FROM @TV t1
LEFT MERGE JOIN @TV t2 ON t1.Id = t2.Id+1 AND t1.ProductId=t2.ProductId
ORDER BY t1.Id
精彩评论