Sql 为上一个值提供endDate

Sql 为上一个值提供endDate,sql,sql-server,Sql,Sql Server,我想在MainAccountNum已经存在时提供一个EndDate。endDate应用于起始日期最早的MainAccountNum 因此,如果我有一个CREATETABLE语句,如下所示: Create Table ods.CustomerId( ScreenDate INT NOT NULL, CustomerNum nvarchar(40) NOT NULL, MainAccountNum nvarchar(40) not null, ServiceNu

我想在MainAccountNum已经存在时提供一个EndDate。endDate应用于起始日期最早的MainAccountNum

因此,如果我有一个CREATETABLE语句,如下所示:

   Create Table ods.CustomerId(
    ScreenDate INT NOT NULL,
    CustomerNum nvarchar(40) NOT NULL,
    MainAccountNum nvarchar(40) not null,
    ServiceNum nvarchar(40) not null,
    StartDate datetime not null,
    EndDate datetime not null,
    UpdatedBy nvarchar(50) not null);
假设我在CustomerNum、MainAccountNum、StartDate和EndDate中遇到如下内容:

1467823,47382906,2019-08-26 00:00:00.000, Null
1467833,47382906,2019-09-06 00:00:00.000, null
当第二条记录与同一个MainAccountNum一起插入时,第一条记录应获取新记录的startDate。startDate有一个默认约束,即GetDat(),因此最后它应该如下所示:

1467823,47382906,2019-08-26 00:00:00.000,2019-09-06 00:00:00.000
1467833,47382906,2019-09-06 00:00:00.000, null

请提供代码示例,说明如何在用于插入新记录的存储过程中实现这一点

begin tran
declare @startDate datetime

select top 1 @oldStartDate = StartDate 
from ods.CustomerId 
where MainAccountNum = @mainAccountNum 
order by StartDate asc

if @@rowcount > 0
    update ods.CustomerId set EndDate = @startDate 
    where MainAccountNum = @mainAccountNum and StartDate = @oldStartDate

insert ... <your new record here>
commit
开始传输
声明@startDate datetime
选择top 1@oldStartDate=StartDate
来自ods.CustomerId
其中maincountnum=@maincountnum
按起始日期asc订购
如果@@rowcount>0
更新ods.CustomerId set EndDate=@startDate
其中maincountnum=@maincountnum和StartDate=@oldStartDate
插入。。。
犯罪

我假设(maincountnum,StartDate)元组是唯一的,可以用作键。如果没有,您必须在update语句中使用唯一的语句。

到目前为止,您都做了些什么?您是否查看了
LEAD
/
LAG
?@Larnu不,我不知道该代码是什么样子的?您的数据模式是一成不变的吗?如果没有,我建议从customer表中删除日期,而是使用Account_Service表记录日期和操作(开始、结束、修改等)。您可以很容易地从中获取开始/结束数据,并且不会以重复的帐户记录结束。您想将此结束日期“应用”到A)查询显示的数据,还是B)在创建新行时修改实际表?