Here's the query that I use for AR Aging queries.
NOTE:
This script (and every other script on this site) is provided 'as-is' and needs to be verified by a qualified accountant.