【问题标题】:SQL set index field based on date fieldSQL根据日期字段设置索引字段
【发布时间】:2011-09-08 20:59:30
【问题描述】:

我希望实现类似于SQL query to populate index field based on groups 的东西。

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

我的表结构是:

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

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

【问题讨论】:

    标签: sql tsql


    【解决方案1】:
    ;with C as
    (
      select DisplayIndex,
             row_number() over (partition by [Group] order by DateCreated desc) as rn
      from Product 
    )
    update C set
      DisplayIndex = rn
    

    【讨论】:

      【解决方案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.

      【讨论】:

        猜你喜欢
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        • 2010-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 2023-04-06
        相关资源
        最近更新 更多