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

时间:2018-09-07 10:40:14

标签: sql sql-server date partitioning

我有下表

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

2 个答案:

答案 0 :(得分:4)

我们可以在此处尝试使用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

答案 1 :(得分:1)

我会使用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;