简体   繁体   中英

Lag to specific value not by row number

DATE    MAKE    MODEL    VALUE   PREV_VALUE  STATUS
01-29   Toyota  Star     1000        -       SOLD
01-29   Audi    Sun      2000        -       SOLD
01-29   Nissan  Moon     3000        -       SOLD
02-29   Toyota  Star     5000       1000     OFFERED
02-29   Toytota Star     12000      1000     WITHDRAWN
02-29   Nissan  Moon     6000       3000     SOLD
03-29   Toyota  Star     7000       1000     SOLD
04-29   Toyota  Star     7000       7000     OFFERED

I want to get the previous value for each model and make where it exists and the Status is 'SOLD'. There could be any number of makes and models.

I need to get the previous sold value of that make and model regardless of the current status. How can I partition to get the previous 'SOLD' values using lag?

You can use lag() with the ignore null s option:

select t.*,
       lag(case when status = 'SOLD' then value end ignore nulls) over (partition by model order by date)
from t;

Here is a db<>fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM