【问题标题】:Historicize a table historicized wrong in SQL历史化 SQL 中历史错误的表
【发布时间】:2021-05-28 15:16:30
【问题描述】:

假设我的表中有以下错误的历史数据:

ID     DATE START      DATE END
1      2020-10-16     2020-12-11
1      2020-11-09     2021-01-02     
1      2020-12-11     2021-01-19
1      2021-01-02     2020-12-11
1      2021-01-19     2050-12-31

我想要的是:

ID     DATE START      DATE END
1      2020-10-16     2020-11-09
1      2020-11-09     2020-12-11     
1      2020-12-11     2021-01-02
1      2021-01-02     2021-01-19
1      2021-01-19     2050-12-31

最后一条记录必须在“2050-12-31”之前结束,并且每个新的开始日期都是上一条记录的结束日期。

假设我有数千条记录的这种情况,所以我不能只进行简单的更新。

非常感谢大家可以帮助我。

【问题讨论】:

  • 如果您需要更新您的数据,您需要使用更新语句。构建一个更正数据的查询,然后将其转换为更新。

标签: sql sql-server database tsql sql-update


【解决方案1】:

试试下面这个脚本-

DEMO HERE

WITH CTE
AS
(
    select ROW_NUMBER() OVER(order by DATE_START) rn,
    * 
    from your_table_name
)


select 
a.id,
a.date_start,
case when b.date_start is null then a.date_end else b.date_start end date_end 
from cte a
left join cte b on a.rn = b.rn-1

【讨论】:

    【解决方案2】:

    似乎一个简单的 LEAD() 函数就可以解决问题:

    INSERT INTO #tmp(ID,[DATE START],[DATE END]) VALUES 
    (1,'2020-10-16','2020-12-11'),
    (1,'2020-11-09','2021-01-02'),     
    (1,'2020-12-11','2021-01-19'),
    (1,'2021-01-02','2020-12-11'),
    (1,'2021-01-19','2050-12-31')
    
    
    SELECT ID,[DATE START], 
    LEAD([DATE START], 1, '12/31/2050') OVER(ORDER BY ID,[DATE START]) [DATE END]
    FROM #tmp
    

    【讨论】:

      【解决方案3】:

      您可以在update 中使用lead() 作为:

      with toupdate as (
            select h.*,
                   lead(date_start, 1, '2050-12-31') over (partition by id order by date_start) as next_date_start
            from historic h
           ) 
      update toupdate
          set date_end = next_date_start
          where date_end <> next_date_start;
      

      Here 是一个 dbfiddle。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多