SQL在新列中创建具有先前日期的新列

时间:2016-08-30 09:03:27

标签: sql sql-server sql-server-2012

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

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

enter image description here

或此链接http://imgur.com/easxkMH

新日期必须特定于该ID

我正在考虑为每个ID和另一个列创建一个新的序列(1,2,3,...)列,其中它增加1(NULL,1,2,3)然后自我创建离开加入。

请就任何其他程序提供建议并提供代码帮助

由于

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:1)

您可以使用ROW_NUMBERs将表格放入CTE,然后将此CTE加入其中:

;WITH cte AS (
SELECT  y.ID,
        y.[DATE],
        ROW_NUMBER() OVER (PARTITION BY y.ID ORDER BY (SELECT NULL)) RN
FROM YourTable y
)

SELECT  c.ID,
        c.[DATE],
        c1.[DATE]
FROM cte c
LEFT JOIN cte c1 
    ON c.ID = c1.ID AND c.RN = c1.RN+1

输出:

ID          DATE        DATE
a2cVqAAl    6/16/2015   NULL
a2cVqAAl    6/24/2015   6/16/2015
a2cVqAAl    6/15/2015   6/24/2015
a36E8AAl    10/16/2015  NULL
a36E8AAl    7/8/2015    10/16/2015
d3yAAA      7/10/2015   NULL
d3yAAA      7/30/2015   7/10/2015
d3yAAA      9/9/2015    7/30/2015
d3yAAA      7/10/2015   9/9/2015
d3yAAA      7/14/2015   7/10/2015
d3yAAA      7/14/2015   7/14/2015