0

When making the "frame" for a windowed analytic function, one can specify a literal number of rows to "look back" over. E.g., the following will get the trailing 26 weeks weekly sales for a households.

,sum(sales) over (partition by household_id order by week_id rows 26 preceding) as x26

But... what if you wanted to look back (or forward) with an offset? E.g., if for week n, you wanted the sales for the 26 weeks that ended 8 weeks before week n? As I was typing this, it occurred to me that I could probably do it in parts. I.e.,

 ,sum(sales) over (partition by household_id order by week_id rows 34 preceding) as x34
 ,sum(sales) over (partition by household_id order by week_id rows 8 preceding) as x8

...and have trailing26_offeset8 = x34 - x8

Hm... Glad I asked. But anyway, do you know if there's an feature that will let me specify the offset right in the partition specification itself?

Thanks!

Chris
  • 1,421
  • 3
  • 18
  • 31

1 Answers1

2

Try using between in the window range specification:

sum(sales) over (partition by household_id
                 order by week_id
                 rows between 34 preceding and 8 preceding
                ) as x34
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Yes, that works and was just what I was looking for! FWIW, my two-part solution came up with the same answer, but this is certainly simpler. Thanks. – Chris Feb 05 '15 at 20:50