简体   繁体   中英

How to get previous record information

I need to retrieve the columns Random_1, Random_2, Random_3 My other table is joining data off the date key 9/25/2016. I also need to see Random_1, Random_2,Random_3 looking at the 9/22/2016. I want to know how to say from my join on date key whatever the date may be show me the previous record information. Dates are dates and I am using Oracle (The dates will change)

How can do this? See link for example

To pull Random_1 for the previous date, you would use the LAG() function, like so:

select ... ,  lag(t1.random_1) over (order by t1.date_key), .....
from  table1 t1 join table2 t2 on t1.date_key = t2.date_key
...

(and same for the other columns). Note that the result of LAG() will, of course, be NULL for the earliest row - since there is no "previous" value. If you want something else for the first row, wrap everything within a COALESCE() .

Also, if you have id 's of some kind and you join by id as well, then you don't want to mix together dates for different id's. The LAG() functions (and almost all other analytic functions) allows you to partition by id in addition to ordering by date. You can read the definition and examples in the Oracle documentation .

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