简体   繁体   English

SQL-基于实体的先前记录的更新记录

[英]SQL - Update Record Based on Entity's Previous Record

I have a temp table that has an entityID, a start date, an end date, and number of days. 我有一个临时表,该表具有一个entityID,一个开始日期,一个结束日期和天数。 I get the number of days by getting the datediff between start and end dates and +1 day. 我通过获取开始日期和结束日期以及+1天之间的datediff来获得天数。 The problem that I am having is when an entity has a second record that has the same start date as its previous end date, I get the number of days as 1 too many. 我遇到的问题是,当一个实体的第二条记录的开始日期与上一个结束日期相同时,我得到的天数太多了1。 ie.: 即:

EntityID    StartDate    EndDate    NumOfDays
--------    ---------    -------    ---------
3414        02/01/2018   02/02/2018    2 
3414        02/02/2018   02/10/2018    9

I need to make the StartDate of the second record to be 02/03/2018 and NumOfDays becomes 8 so that the whole range of days is 10 which would be correct. 我需要将第二条记录的StartDate设置为02/03/2018,并且NumOfDays变为8,以便整个天数范围是10,这是正确的。 The temp table is ordered on EntityID, StartDate. 临时表在EntityID StartDate上排序。 There would be thousands of records in the table and maybe a few hundred that has this case. 表中将有成千上万的记录,而在这种情况下可能有数百条记录。 I only need to change the start date if that entity's previous end date is the same. 如果该实体的上一个结束日期相同,则仅需要更改开始日期。

Should I do a loop? 我应该循环吗? Cursor? 光标? Or is there a better way? 或者,还有更好的方法?

We are on SQL Server 2014 我们正在使用SQL Server 2014

First, it seems that you should be calculating the number of days without the end date. 首先,似乎您应该在计算没有结束日期的天数。 That would solve the problem. 这样可以解决问题。 But, that might not work. 但是,这可能行不通。

You can use an updatable CTE: 您可以使用可更新的CTE:

with toupdate as (
      select t.*, lag(end_date) over (partition by entityid order by start_date) as prev_end_date
      from t
     )
update toupdate
     set numofdays = numofdays - 1
     where prev_end_date = end_date;
Declare @t TABLE (EntityID  INT,   StartDate DATE,   EndDate DATE)
INSERT INTO @t VALUES
(3414  ,'02/01/2018','02/02/2018'), 
(3414  ,'02/02/2018','02/10/2018');

WITH x AS (
      SELECT t.*
            , CASE WHEN LAG(EndDate) OVER (PARTITION BY EntityID ORDER BY StartDate) >= StartDate
                   THEN DATEADD( DAY , 1 , LAG(EndDate) OVER (PARTITION BY EntityID ORDER BY StartDate))
              ELSE StartDate END NewStartDate
      FROM @t t
     )
SELECT EntityID 
    , NewStartDate 
    , EndDate 
    , DATEDIFF(DAY, NewStartDate , EndDate) + 1 AS NumOfDays 
FROM X 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM