Help Avoid Using CURSOR to Calculate Columns

I have a group of records in a table variable:

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 the identifier column that I added to my table variable (will explain why I need it at the moment). ProductId is a Product . Rank is a value that represents the ranking of a product at a given point in time. RankCreated is the time at which Product was ranked .

What am I trying to do:

Calculate the "movement" between each product rank for each product. Where "movement" is defined as current - previous.

So, the "calculated column" will 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

Id, .

temp:

insert into @rankhistories (productid, [rank], [rankcreated])
select a.ProductId, b.[rank]
from dbo.ProductRankHistories b
inner join dbo.Products a on a.ProductId = b.ProductId
order by a.ProductId, b.RankCreated

, . 6000+ , 5 , .

- ?

+3
1
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
+4

All Articles