Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

pyspark - SQL using lag function

What i want to do is to create a column 'ID_DESLIG' with the following rules:

  • when STATE is 'LIGADO' then ID_DESLIG will be the id of the previous STATE is 'DESLIGADO', for the same panel;

  • when STATE is 'DESLIGADO' then ID_DESLIG will be the id of the current row;

An example of what i want

example

Thanks in advance for the help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you want:

select t.*,
       (case when state = 'DESLIGADO' then id
             else max(case when state = 'DESLIGADO' then id end) over (order by id)
        end) as desligado_id
from t;

In turn, this can be simplified to:

max(case when state = 'DESLIGADO' then id end) over (order by id)

You could phrase this using lag() but only if you know that the states are always interleaved.

In standard SQL (and some databases), this could also be expressed as:

max(id) filter (where state = 'DESLIGADO') over (order by id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...