Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...