Hello,
I am database administrator use TSQL in sql server, mysql, oracle, postgres..
used to create so many procedure, queries, function..
I already read your attach files, it is clearly and not complex
So I can help you do it within 2hrs from now
Please contact to me
Thank you