我希望能达到与SQL query to populate index field based on groups类似的功能。
唯一的区别是我想根据现有的日期字段设置索引字段。
我的表结构是:
Product
-------
Group
Name
DateCreated
DisplayIndex
所以我需要按“Group”进行分组,并根据DateCreated日期更新该组中项目的DisplayIndex。
答案 0 :(得分:3)
;with C as
(
select DisplayIndex,
row_number() over (partition by [Group] order by DateCreated desc) as rn
from Product
)
update C set
DisplayIndex = rn
答案 1 :(得分:2)
您可以使用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]