Teradata equivalent for lead and lag function of oracle

user708477 picture user708477 · Nov 14, 2011 · Viewed 21.8k times · Source

I have been working ot see the equivalent function for Oracle lead and lag function.

The oracle lead would look like

LEAD(col1.date,1,ADD_MONTHS(col1.DATE,12)) 
OVER(Partition By tab.a,tab.b,tab.c Order By tab.a)-1 END_DATE

LAG(col1.DATE + 7,1,col1.DATE-1) 
OVER(partition by tab.a,tab.b Order By tab.b) LAG_DATE

Any better idea

Answer

Rob Paller picture Rob Paller · Nov 15, 2011

I believe you can take the following SQL as a basis and modify it to meet your needs:

SELECT CALENDAR_DATE
     , MAX(CALENDAR_DATE)
       OVER(PARTITION BY 1 ORDER BY CALENDAR_DATE
            ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS Lag_ --Yesterday
     , MIN(CALENDAR_DATE)
            OVER(PARTITION BY 1 ORDER BY CALENDAR_DATE
            ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS Lead_ --Tomorrow
FROM SysCalendar.CALENDAR
WHERE year_of_calendar = 2011
  AND month_of_year = 11

NULL is returned when there is no record before or after and can be addressed with a COALESCE as necessary.

EDIT In Teradata 16.00 LAG/LEAD functions were introduced.