Go to the Free Software Add Ons at the top of this page. Find and download "Sales Report." Read the code and you'll see how some of the things you're asking about can be accomplished.