【问题标题】:How can I update the end date to the value of the following records start date?如何将结束日期更新为以下记录开始日期的值?
【发布时间】:2013-06-10 16:16:00
【问题描述】:

我有一个表[RoleHistories] 带有列的表:

[RoleHistoryId] [PersonId] [开始] [结束]

开始列填充了日期。结束列为空。每人多排。我需要更新结束列以具有作为下一条记录的开始日期的日期。如果没有后续记录,则结尾应保持为空

例如

RoleHistoryId = 999, PersonId =1, Start=2009-1-1, End=null
RoleHistoryId = 2677, PersonId =1, Start=2011-5-1, End=null
RoleHistoryId = 4637, PersonId =1, Start=2013-9-1, End=null

我想要

RoleHistoryId = 999, PersonId =1, Start=2009-1-1, End=2011-5-1
RoleHistoryId = 2677, PersonId =1, Start=2011-5-1, End=2013-9-1
RoleHistoryId = 4637, PersonId =1, Start=2013-9-1, End=null

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:
    UPDATE rh1 
    SET    End = (SELECT Min(Start) 
                  FROM   RoleHistories rh2 
                  WHERE  rh1.Personid = rh2.Personid 
                         AND rh1.Start < rh2.Start) 
    FROM RoleHistories rh1
    WHERE End IS NULL
    

    【讨论】:

    • 在 MS SQL Server 中似乎不是有效的语法
    • 哎呀,我在打电话,否则我会在 SQL-fiddle 上检查它。试试这个。
    猜你喜欢
    • 2023-04-07
    • 2022-01-23
    • 2021-05-16
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多