2010-10-18 2 views
1
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 
+1

Qu'est-ce que votre structure de la table ressemble? Aussi, quelle version de SQL Server? – LittleBobbyTables

Répondre

2

En supposant une table appelée SampleData, et les colonnes appelées Date et Starting, vous pouvez le faire pour interroger la table:

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 

Qui reviendra:

Date  Starting  Ending 

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

Si vous souhaitez mettre à jour la table à la place, vous pouvez effectuer les opérations suivantes:

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 
2

ne pas être la meilleure solution, mais suivante fonctionnerait si son une opération de temps et les performances ne sont pas une préoccupation

CREATE FONCTION GetPreviousVal
(
@ PrevVal int ) int RETOURS AS BEGIN

DECLARE @ReturnVal INT 

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


RETURN @ReturnVal 

FIN

GO

Maintenant, utilisez ci-dessus fonction pour mettre à jour vos données

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