代码之家  ›  专栏  ›  技术社区  ›  not_ur_avg_cookie

更新每个群集的最后一条记录

  •  2
  • not_ur_avg_cookie  · 技术社区  · 6 年前

    我有一个表,并且我已经为每个产品集群中的下一个日期创建了潜在客户值。除此之外,我还创建了一个delta值,显示日期和潜在客户日期之间的差异。

    +---------+------------+------------+------------+
    | Product |    Date    |  LeadDate  | delta_days |
    +---------+------------+------------+------------+
    | A       | 2018-01-15 | 2018-01-23 | 8          |
    | A       | 2018-01-23 | 2018-02-19 | 27         |
    | A       | 2018-02-19 | 2017-05-25 | -270       |
    | B       | 2017-05-25 | 2017-05-30 | 5          |
    | B       | 2017-05-30 | 2016-01-01 | -515       |
    | C       | 2016-01-01 | 2016-01-02 | 1          |
    | C       | 2016-01-02 | 2016-01-03 | 1          |
    | C       | 2016-01-03 | NULL       | NULL       |
    +---------+------------+------------+------------+
    

    我要做的是,我需要更新每个产品集群的最后一条记录,并将Lead-Date和Delta-Days设置为空。我该怎么做?

    这是我的目标:

    +---------+------------+------------+------------+
    | Product |    Date    |  LeadDate  | delta_days |
    +---------+------------+------------+------------+
    | A       | 2018-01-15 | 2018-01-23 | 8          |
    | A       | 2018-01-23 | 2018-02-19 | 27         |
    | A       | 2018-02-19 | NULL       | NULL       |
    | B       | 2017-05-25 | 2017-05-30 | 5          |
    | B       | 2017-05-30 | NULL       | NULL       |
    | C       | 2016-01-01 | 2016-01-02 | 1          |
    | C       | 2016-01-02 | 2016-01-03 | 1          |
    | C       | 2016-01-03 | NULL       | NULL       |
    +---------+------------+------------+------------+
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   dfundako    6 年前

    Lag/Lead

    LAG (scalar_expression [,offset] [,default])  
        OVER ( [ partition_by_clause ] order_by_clause )  
    

    [default]

    SELECT date, 
    LEAD([date], 1, NULL) OVER(PARTITION BY Product ORDER BY [date]) as your_new_col
    

        2
  •  1
  •   Yogesh Sharma    6 年前

    cte last_value()

    with updatable as (
            select *, last_value(date) over (partition by product order by date) as last_val
            from table 
    )
    
    update updatable 
    set LeadDate = null, delta_days = null
    where Date = last_val;