this query is working perfectly fine .but i dont get the formula .how is it working . can anyone kindly explain this formula or can share any reference link where i find this . (Note : this question is asked after investing alot of time to find the explanation of this formula ).

What I have tried:

formula is working perfectly fine . but needs explanation