[英]Get previous value/next value in DB2 SQL
I am trying to get the value of some data from the following example table: 我试图从下面的示例表中获取某些数据的值:
DEAL_ID | DISC | EFF_DATE | EXP_DATE
100 | 2 | 01-01-19 | 31-01-2019
101 | 2 | 01-02-19 | 15-02-2019
103 | 3 | 01-03-19 | 31-03-2019
104 | 4 | 01-04-19 | 25-04-2019
As seen, there is a time period between deal_id 101 and 103, from 16-2-2019 to 28-2-2019 that has no assigned DISC value. 如图所示,deal_id 101和103之间有一个时间段,从16-2-2019到28-2-2019,没有分配的DISC值。 In this case, for any period that has no assigned DEAL/DISC, it would take the last EXP_DATE that exists beforethat time period, and change the EXP_DATE to the next EFF_DATE, covering all the time period that didn't have an asssigned one, ending the table like this:
在这种情况下,对于任何未分配DEAL / DISC的时间段,它将采用该时间段之前存在的最后一个EXP_DATE,并将EXP_DATE更改为下一个EFF_DATE,覆盖所有未分配的时间段,像这样结束表格:
DEAL_ID | DISC | EFF_DATE | EXP_DATE
100 | 2 | 01-01-19 | 31-01-2019
101 | 2 | 01-02-19 | 28-02-2019
103 | 3 | 01-03-19 | 31-03-2019
104 | 4 | 01-04-19 | 25-04-2019
I did find there is a LEAD/LAG function for DB2, however, it is not valid/doesn't work/not recognized in the version I am using (am not sure which version is, btw). 我确实找到了DB2的LEAD / LAG函数,但是在我使用的版本中它无效/不起作用/无法识别(不知道哪个版本是btw)。
The current code I have is: 我当前的代码是:
SELECT A.deal_id as deal_id, A.vendr_nbr, A.vndr_deal_eff_date, A.vndr_deal_exp_date, (YEAR(vndr_deal_eff_date) * 10000 + MONTH(vndr_deal_eff_date)*100 + DAY(vndr_deal_eff_date)) limitDate1EFF, (YEAR(vndr_deal_exp_date) * 10000 + MONTH(vndr_deal_exp_date)*100 + DAY(vndr_deal_exp_date)) limitDate2EXP, B.DISC_CHRG_ID, B.DISCOUNT_VALUE, C.VENDR_DEPT_NBR
FROM workdbo.vendor_deal A
LEFT JOIN workdbo.DDA_DISC_CHRG_TIER B ON A.deal_id = B.DISC_CHRG_ID
LEFT JOIN workdbo.DEAL_DEPT C ON A.deal_id = C.deal_id
Any help would be appreciated. 任何帮助,将不胜感激。
Note: EFF_DATE and EXP_DATE are both date
data type, and are recognized as such. 注意:EFF_DATE和EXP_DATE都是
date
数据类型,因此被识别。 From the query posted I have, A.vndr_deal_eff_date, A.vndr_deal_exp_date
are the dates I am using. 根据我发布的查询,
A.vndr_deal_eff_date, A.vndr_deal_exp_date
是我使用的日期。
(If the post needs changing to fit stackoverflow guidelines, please do tell what should I edit/add/etc, instead of just leaving a -1, thanks) (如果帖子需要更改以适合stackoverflow准则,请告诉我应该编辑/添加/等内容,而不是只留下-1,谢谢)
Based on your "example" table, you should just use lead()
: 根据您的“示例”表,您应该只使用
lead()
:
select . . . ,
add_days(lead(eff_date) over (order by eff_date), -1)
from example;
I'm not sure what your query -- which mentions 3 tables and doesn't seem to use a date
data type -- has to do with the question. 我不确定您的查询(涉及3个表并且似乎未使用
date
数据类型)与该问题有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.