我们有SQL Server 2016.多年来我们有自己的历史。现在我想将历史数据转换为新格式,并将CustomAudit表用作具有已有历史数据的历史表。
首先会有一个小例子,然后是问题
CREATE TABLE [dbo].[client]
(
idclient int identity(1,1) primary key,
clientData nvarchar (400)
) ON [PRIMARY]
INSERT [dbo].[client] ( clientData ) values ('some-12221')
INSERT [dbo].[client] ( clientData ) values ('some-22111')
alter table [client]
add
StartTime datetime2 GENERATED ALWAYS AS ROW START DEFAULT GETUTCDATE(),
EndTime datetime2 GENERATED ALWAYS AS ROW END DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (StartTime,EndTime)
CREATE TABLE [dbo].[CustomAydit_client]
(
idclient int,
dEditDate datetime NOT NULL DEFAULT (getdate()),
clientData nvarchar (400)
) ON [PRIMARY]
alter table [CustomAydit_client]
add
StartTime datetime2 GENERATED ALWAYS AS ROW START DEFAULT GETUTCDATE(),
EndTime datetime2 GENERATED ALWAYS AS ROW END DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME (StartTime,EndTime)
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2016-05-06 10:08:11.923' AS DateTime)), 'some-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2016-02-11 10:08:11.923' AS DateTime)), 'some-211')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (2, (CAST(N'2016-12-06 10:08:11.923' AS DateTime)), 'some-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2015-05-19 10:08:11.923' AS DateTime)), 'some-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (2, (CAST(N'2016-05-06 10:08:11.923' AS DateTime)), 'some-211')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2016-05-26 10:08:11.923' AS DateTime)), 'some-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (2, (CAST(N'2016-05-06 10:08:11.923' AS DateTime)), 'some33-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2016-05-06 10:08:11.923' AS DateTime)), 'some3-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate,clientData)
VALUES (2, (CAST(N'2016-11-16 10:08:11.923' AS DateTime)), 'some-1')
INSERT [dbo].[CustomAydit_client] (idclient, dEditDate, clientData)
VALUES (1, (CAST(N'2016-02-17 10:08:11.923' AS DateTime)), 'some-1')
我需要行和行的StartTime。
对于客户1,我想获取字段DeditDate的第2行数据
更新此数据第1行字段EndTime
最后一行,客户端不应该有EndTime,这个确定9999-12-31 23:59:59.9999999
SELECT
ROW_NUMBER() OVER( PARTITION BY idclient ORDER BY dEditDate) AS tempid,
idclient,
dEditDate,
StartTime, EndTime
FROM
[dbo].[CustomAydit_client]
ORDER BY
idclient, dEditDate
答案 0 :(得分:1)
您可以使用lead
函数从下一行获取值作为结束时间。
select
ROW_NUMBER() OVER(PARTITION BY idclient ORDER BY dEditDate) AS tempid,
idclient,
dEditDate,
StartTime,
lead(dEditDate) over(PARTITION BY idclient ORDER BY dEditDate) as EndTime
from [dbo].[CustomAydit_client]
order by idclient, dEditDate