帮助避免使用 CURSOR 进行列计算
我在表变量中有一堆记录,如下所示:
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 是我添加到表变量中的标识列(稍后将解释为什么我需要它)。 ProductId 是一个产品。 排名是代表产品在给定时间的排名的值。 RankCreated 是产品排名的时间。
我想做什么:
计算每个产品的每个产品排名之间的“移动”。其中“移动”定义为当前 - 先前。
因此,“计算列”将如下所示:
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 列,以便我可以使用它来获取上一条记录。
这是我将数据放入临时表的方法:
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 秒,这是不可接受的。
有人可以帮忙吗?
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
inner 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)