如何将上一行值分配给下一行

时间:2010-10-18 17:23:54

标签: sql-server

Date       Starting      Ending

10/01/2010      0            100
10/02/2010     100           200
10/03/2010     200           300
10/04/2010     300             0   

the table has only one column that is ending and i need the output similar to one shown above and using sqlserver 2005

2 个答案:

答案 0 :(得分:2)

可能不是最佳解决方案,但如果一次性操作和性能不是问题,则可以使用以下方法

创建功能GetPreviousVal

    @PrevVal int ) 返回int 如 BEGIN

DECLARE @ReturnVal INT

SELECT TOP 1 @ReturnVal = Ending 
FROM RowVal
WHERE Ending < @PrevVal
ORDER BY Ending DESC


RETURN @ReturnVal

END

GO

现在,使用上述功能更新您的数据

UPDATE RowVal
SET Starting = ISNULL(dbo.GetPreviousVal(Ending),0)

答案 1 :(得分:2)

假设有一个名为SampleData的表,以及名为DateStarting的列,您可以执行此操作来查询该表:

SELECT S1.Date, S1.Starting, ISNULL(S2.Starting, 0) as Ending
FROM SampleData S1
LEFT OUTER JOIN
(
    SELECT *
    FROM SampleData
) S2
ON DATEADD(d, 1, S1.Date) = S2.Date

将返回:

Date       Starting      Ending

10/01/2010      0            100
10/02/2010     100           200
10/03/2010     200           300
10/04/2010     300             0 

如果您想更新表格,可以执行以下操作:

UPDATE SampleData
SET Starting = Ending
FROM SampleData S3 
INNER JOIN
(
    SELECT S1.Date, ISNULL(S2.Starting, 0) as Ending
    FROM SampleData S1
    LEFT OUTER JOIN
    (
        SELECT *
        FROM SampleData
    ) S2
    ON DATEADD(d, 1, S1.Date) = S2.Date
) S4 ON S3.Date = S4.Date