【问题标题】:Adding a Date column based on the next row date value根据下一行日期值添加日期列
【发布时间】:2013-03-01 03:36:04
【问题描述】:

我使用的是 SQL Server 2005。从下面的 tbl_temp 表中,我想根据下一行的 StartDate 减去 1 天添加一个 EndDate 列,直到 AID 和 UID 组合发生变化。这个计算出来的 EndDate 将作为 EndDate 转到它上面的行。 AID 和 UID 组的最后一行将获取系统日期作为其 EndDate。该表必须按 AID、UID、StartDate 顺序排序。感谢您的帮助。

-- tbl_temp

援助 UID 开始日期 1 1 2013-02-20 2 1 2013-02-06 1 1 2013-02-21 1 1 2013-02-27 1 2 2013-02-02 1 2 2013-02-04

-- 需要结果

AID UID 开始日期 结束日期 1 1 2013-02-20 2013-02-20 1 1 2013-02-21 2013-02-26 1 1 2013-02-27 系统日期 1 2 2013-02-02 2013-02-03 1 2 2013-02-04 系统日期 2 1 2013-02-06 系统日期

【问题讨论】:

    标签: sql sql-server-2005


    【解决方案1】:

    最简单的方法是使用相关子查询:

    select t.*,
           (select top 1 dateadd(day, -1, startDate )
            from tbl_temp t2
            where t2.aid = t.aid and
                  t2.uid = t.uid and
                  t2.startdate > t.startdate
           ) as endDate
    from tbl_temp t
    

    要获取当前日期,请使用isnull()

    select t.*,
           isnull((select top 1 dateadd(day, -1, startDate )
                   from tbl_temp t2
                   where t2.aid = t.aid and
                         t2.uid = t.uid and
                         t2.startdate > t.startdate
                   ), getdate()
                  ) as endDate
    from tbl_temp t
    

    通常,我会推荐coalesce() 而不是isnull()。但是,在某些版本的 SQL Server 中存在一个错误,它对第一个参数求值两次。通常,这并没有什么区别,但对于子查询却有影响。

    最后,sysdate 的使用让我想到了 Oracle。同样的方法也适用于那里。

    【讨论】:

    • 第二个效果很好。只是一个额外的字符,我去掉了“as endDate”前面的“)”,这样其他人也可以受益。非常感谢。
    【解决方案2】:
    ;WITH x AS
    (
        SELECT AID, UID, StartDate, 
            ROW_NUMBER() OVER(PARTITION BY AID, UID ORDER BY StartDate) AS rn
        FROM tbl_temp
    )
    SELECT x1.AID, x1.UID, x1.StartDate, 
        COALESCE(DATEADD(day,-1,x2.StartDate), CAST(getdate() AS date)) AS EndDate
    FROM x x1
    LEFT OUTER JOIN x x2 ON x2.AID = x1.AID AND x2.UID = x1.UID
        AND x2.rn = x1.rn + 1
    ORDER BY x1.AID, x1.UID, x1.StartDate
    

    SQL Fiddle example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 2012-02-09
      • 2020-01-16
      • 1970-01-01
      • 2017-11-03
      • 2021-09-08
      相关资源
      最近更新 更多