使用窗口函数更新具有多个值的列

Posted

技术标签:

【中文标题】使用窗口函数更新具有多个值的列【英文标题】:update column mith multple values using window function 【发布时间】:2019-09-23 14:46:15 【问题描述】:

我有下表,其中包含大约。 100,000 行,每个 id 都需要更新。

组织表 A

id    start_dt    end_dt      cust_start_dt    cust_end_dt
 1    8/1/2008    9/12/2019   8/7/2008          9/12/2019
 1    9/17/2019   9/20/2019   9/17/2019         12/31/9999
 1    9/21/2019   12/31/9999  9/17/2019         12/31/9999

表 A 应如下所示...

id    start_dt    end_dt      cust_start_dt    cust_end_dt
 1    8/1/2008    9/16/2019   9/17/2019         12/31/9999
 1    9/17/2019   9/20/2019   9/17/2019         12/31/9999
 1    9/21/2019   12/31/9999  9/17/2019         12/31/9999

sql

select
id
start_dt,
case
when lead(start_dt) over (partition by id order by start_dt) - end_dt > 1 then lead(start_dt) over (partition by id order by start_dt) - 1
else end_dt
end end_dt, 
first_value(start_dt) over (partition by id order by start_dt) as cust_start_dt,
first_value(end_dt) over (partition by id order by start_dt desc) as cust_end_dt

from a

然后我如何进行上述查询并更新表 A?

【问题讨论】:

【参考方案1】:

使用merge 声明

Merge into a a
Using
(select id
        start_dt,
        case 
          when lead(start_dt) over (partition by id order by start_dt) - end_dt > 1 
          then lead(start_dt) over (partition by id order by start_dt) - 1
          else end_dt
        end end_dt, 
        first_value(start_dt) over (partition by id order by start_dt) as cust_start_dt,
        first_value(end_dt) over (partition by id order by start_dt desc) as cust_end_dt
   from a) b
On (a.id = b.id
    And a.start_dt = b.start_dt)
When matched then
Update set
  A.end_dt = b.end_dt,
  A.cust_start_dt = b.cust_start_dt,
  A.cust_end_dt = b.cust_end_dt

干杯!!

【讨论】:

以上是关于使用窗口函数更新具有多个值的列的主要内容,如果未能解决你的问题,请参考以下文章

窗口函数 LAG 可以引用正在计算哪个值的列吗?

创建“部分”窗口函数以更新 SQL Server 中的数据

在窗口函数中计算具有相等值的行

当前行和上一行之间具有特定值的窗口函数

Pyspark - 如何拆分具有 Datetime 类型的结构值的列?

SQL Server SUM IF 使用具有多个条件的窗口函数