Calculate previous week data in Teradata

user3438498 picture user3438498 · Jun 1, 2015 · Viewed 7.5k times · Source

How to calculate prior 7 days data (Sunday-Saturday of the previous week). on whatever day of week it is run it should always give Sunday-Saturday of the previous week. thanks

Answer

dnoeth picture dnoeth · Jun 1, 2015

What's your Teradata release?

TD14 supports NEXT_DAY, which returns the first "weekday" later than the date specified:

SELECT NEXT_DAY(CURRENT_DATE, 'sun'),    -- next sunday
       NEXT_DAY(CURRENT_DATE, 'sun')-14, -- previous week's sunday
       NEXT_DAY(CURRENT_DATE, 'sun')-8   -- previous week's saturday

Edit:

In TD13 you can subtract the day of week to get the previous week's end date, e.g. (CURRENT_DATE - DATE '0001-01-01') MOD 7 + 1 returns 1 to 7 for Monday to Sunday based on the known Monday '0001-01-01'.

Modified to your needs (week starts on Sunday) this results in:

SELECT
   CURRENT_DATE - ((CURRENT_DATE - DATE '0001-01-07') MOD 7 + 7),  -- previous week's Sunday 
   CURRENT_DATE - ((CURRENT_DATE - DATE '0001-01-07') MOD 7 + 1)   -- previous week's Saturday