Sql-Server-2008-R2
根據先前記錄中另一列的日期將日期增加 1 天
我使用的是SQL Server 2008 R2,我沒有 LAG 和 LEAD 功能。
我有這個初始表,我需要 StartDate 等於上一條記錄的 EndDate 加上 1 天。見結果表。
問候, 埃利奧·費爾南德斯
試試這個自我加入:
CREATE TABLE [dbo].[Table_1]( [id] [int] IDENTITY(1,1) NOT NULL, [date] [datetime2](5) NULL, CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ( [id] ASC ) ) ON [PRIMARY]
一些數據:
SET IDENTITY_INSERT [dbo].[Table_1] ON INSERT [dbo].[Table_1] ([id], [date]) VALUES (1, CAST(N'2021-01-01T00:00:00.0000000' AS DateTime2)) INSERT [dbo].[Table_1] ([id], [date]) VALUES (2, CAST(N'2021-01-03T00:00:00.0000000' AS DateTime2)) INSERT [dbo].[Table_1] ([id], [date]) VALUES (3, CAST(N'2021-01-06T00:00:00.0000000' AS DateTime2)) INSERT [dbo].[Table_1] ([id], [date]) VALUES (4, CAST(N'2021-01-10T00:00:00.0000000' AS DateTime2)) INSERT [dbo].[Table_1] ([id], [date]) VALUES (5, CAST(N'2021-01-20T00:00:00.0000000' AS DateTime2)) SET IDENTITY_INSERT [dbo].[Table_1] OFF
這個查詢:
select t.id,t.date as [from], tnext.date as [to] from table_1 as t left join table_1 as tnext on t.id = tnext.id -1 order by 1