SQL集索引字段基于日期字段

时间:2011-09-08 12:36:21

标签: sql tsql

我希望能达到与SQL query to populate index field based on groups类似的功能。

唯一的区别是我想根据现有的日期字段设置索引字段。

我的表结构是:

Product
-------
Group
Name
DateCreated
DisplayIndex

所以我需要按“Group”进行分组,并根据DateCreated日期更新该组中项目的DisplayIndex。

2 个答案:

答案 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]

Example on SE Data.