【发布时间】:2011-09-08 20:59:30
【问题描述】:
我希望实现类似于SQL query to populate index field based on groups 的东西。
唯一的区别是我想根据现有的日期字段设置索引字段。
我的表结构是:
Product
-------
Group
Name
DateCreated
DisplayIndex
所以我需要按“组”分组,并根据 DateCreated 日期更新该组中项目的 DisplayIndex。
【问题讨论】:
我希望实现类似于SQL query to populate index field based on groups 的东西。
唯一的区别是我想根据现有的日期字段设置索引字段。
我的表结构是:
Product
-------
Group
Name
DateCreated
DisplayIndex
所以我需要按“组”分组,并根据 DateCreated 日期更新该组中项目的 DisplayIndex。
【问题讨论】:
;with C as
(
select DisplayIndex,
row_number() over (partition by [Group] order by DateCreated desc) as rn
from Product
)
update C set
DisplayIndex = rn
【讨论】:
您可以使用 row_number 为每个 Group 的行编号:
update p
set DisplayIndex = pn.rn
from Product p
join (
select row_number() over (partition by [Group]
order by DateCreated desc) as rn
, *
from Product
) as pn
on p.[Group] = pn.[Group]
and p.[Name] = pn.[Name]
【讨论】: