SQL-可能是LAG函数,需要语法调整

时间:2018-11-13 16:46:53

标签: sql

我的数据看起来像这样

ID     Thing   Date  
123    0       1/1/2018     
123    0       1/3/2018   
123    0       1/4/2018       
123    1       1/5/2018       
123    1       1/6/2018   
456    0       1/2/2018   
456    0       1/3/2018   
456    0       1/4/2018   
789    0       1/2/2018   
789    0       1/3/2018   
789    1       1/4/2018  

我希望在“事物”列中获得第一条记录,其中前一条记录为0。所以我的输出应类似于

ID     Thing   Date  
123    0       1/4/2018     
123    1       1/5/2018  
789    0       1/3/2018
789    1       1/4/2018

我已经研究了LAG函数,但是我无法获得正确的语法

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果您想要 just “ 1”,则:

select distinct on (id) t.*
from (select t.*,
             lag(thing) over (partition by id order by date) as prev_thing
      from t
     ) t
where prev_thing = 0 and thing = 1
order by id, date;

但是,您似乎也希望在之前行。当id的开头不是“ 1”时(例如您的所有示例),并且所有内容均为“ 0”或“ 1”时,以下方法起作用:

select t.*
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from t
      where t.date <= (select min(t2.date) from t t2 where t2.id = t.id and t2.thing = 1)
      ) t
where seqnum <= 2;

这个想法是使所有行都达到并包括第一个“ 1”,然后取最后两行。

这是一个更通用的解决方案:

select t.*
from (select t.*,
             lag(thing) over (partition by id order by date) as prev_thing,
             count(*) filter (where thing = 1) over (partition by id order by date rows between unbounded preceding and 1 following) as thing1_counter
      from t
     ) t
where (prev_thing = 0 and thing = 1 and thing1_counter = 1) or
      (thing = 0 and thing1_counter = 1);