Question wrt Lag working dynamically with period type

I would look at this article!

It should have everything you are looking for!