代码之家  ›  专栏  ›  技术社区  ›  A.Papa

按组从递归事件中获取第一个日期

  •  0
  • A.Papa  · 技术社区  · 7 年前

    ID  Date    Event
    1   1990-01-01  1
    1   1990-01-02  0
    1   1990-01-03  1
    2   1990-02-01  0
    2   1990-02-02  1
    2   1990-02-03  1
    

    我想创建一个新的列,其中表示事件列为1的日期,例如:

    ID  Date    Event   Fist Event date
    1   1990-01-01  1   1990-01-01
    1   1990-01-02  0   1990-01-01
    1   1990-01-03  1   1990-01-01
    2   1990-02-01  0   1990-02-02
    2   1990-02-02  1   1990-02-02
    2   1990-02-03  1   1990-02-02
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Tim Biegeleisen    7 年前

    我们可以试着用 MIN 作为分析函数:

    SELECT
        ID,
        Date,
        Event,
        MIN(CASE WHEN Event = 1 THEN Date END) OVER (PARTITION BY ID) AS First_Event_Date
    FROM yourTable
    ORDER BY
        ID,
        Date;
    

    enter image description here

    Demo

        2
  •  1
  •   Yogesh Sharma    7 年前

    outer apply

    select t.*, t1.Date as Fist_Event_date
    from table t outer apply
         ( select top (1) t1.*
           from table t1 
           where t1.id = t.id and t1.event = 1
           order by t1.date 
         ) t1;