簡體   English   中英

SQL-可能是LAG函數,需要語法調整

[英]SQL - Probably LAG function, need syntax adjustment

我的數據看起來像這樣

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”,則:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM