SQL 在新列中使用以前的日期创建新列 [英] SQL Creating a new column with previous dates in new column

查看:37
本文介绍了SQL 在新列中使用以前的日期创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 SQL Server(彩色编码)中得到以下结果

I would Like get below result in SQL Server (Color Coded)

所需的列是我希望日期的方式:

The Column Required is How I would like my Dates to be:

或者这个链接http://imgur.com/easxkMH

新日期必须特定于该 ID

The new dates have to be specific to that ID

我正在考虑为每个 ID 创建一个序列 (1, 2, 3,...) 编号的新列和另一列增加 1 (NULL, 1, 2, 3) 然后做一个自我左连接.

I was thinking of creating a new column of sequence(1, 2, 3,...) number per ID and another column where it is incremented by 1 (NULL, 1, 2, 3) and then doing a self left join.

请对任何其他程序提出建议并帮助代码

Please advice on any other procedure and help with the code

谢谢

推荐答案

可以使用 LEADLAG

语法

LEAD (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

LAG (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

SELECT    Id, Date
        , LEAD(Date) OVER (ORDER BY Id) AS [Next Date]
        , LAG(Date) OVER (ORDER BY Id) AS [Prev Date]
        , LEAD(Date, 2) OVER (ORDER BY Id) AS [2nd Next Date]
        , LAG(Date, 2) OVER (ORDER BY Id) AS [2nd Prev Date]
        , LEAD(Date, 2, 0) OVER (ORDER BY Id) AS [2nd Next Date]
        , LAG(Date, 2, 0) OVER (ORDER BY Id) AS [2nd Prev Date]
FROM    @Test_table

这篇关于SQL 在新列中使用以前的日期创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆