简体   繁体   English

如何获取以前的记录信息

[英]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. 我需要检索Random_1,Random_2,Random_3列我的其他表正在加入日期键9/25/2016的数据。 I also need to see Random_1, Random_2,Random_3 looking at the 9/22/2016. 我还需要查看2016年9月22日的Random_1,Random_2,Random_3。 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) 日期是日期,我使用的是Oracle(日期会发生变化)

How can do this? 怎么办呢? See link for example 例如,请参阅链接

To pull Random_1 for the previous date, you would use the LAG() function, like so: 要将Random_1拉到上一个日期,您可以使用LAG()函数,如下所示:

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. 请注意,对于最早的行, LAG()的结果当然是NULL - 因为没有“previous”值。 If you want something else for the first row, wrap everything within a COALESCE() . 如果您想要第一行的其他内容,请将所有内容包装在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. 另外,如果你有id “某种S和您加入id为好,那么你不希望为不同的ID的日期混合在一起。 The LAG() functions (and almost all other analytic functions) allows you to partition by id in addition to ordering by date. 除了按日期排序之外, LAG()函数(以及几乎所有其他分析函数)允许您partition by id进行partition by id You can read the definition and examples in the Oracle documentation . 您可以阅读Oracle文档中的定义和示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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