If you spend some time looking at Sales Report, you can see how it's done.