The following is a complete mock-up of a real situation, so I hope I haven't screwed anything up by trying to translate a much more complex situation into this fake one (syntax, naming, etc.). Anyway, I'm not sure how to fix my problem, but here goes:From this "sales" table:sale_id date salesperson sale_$1 1/1/2006 bob 202 1/2/2006 joe 903 1/2/2006 bob 204 1/3/2006 tom 305 1/4/2006 bob 706 2/1/2006 bob 107 2/1/2006 tom 408 2/2/2006 bob 109 2/3/2006 gus 60
I'd like to get the following output from a select query:salesperson salesperson jan06_sales jan06_$ feb06_sales feb06_$bob bob 3 110 2 20 gus 0 0 1 60joe 1 90 0 0tom tom 1 30 1 40
Here's where I'm currently at:select jan06.salesperson, feb06.salesperson, count(jan06.sale_id) as 'jan06_sales', sum(jan06.sale_$) as 'jan06_$', count(feb06.sale_id) as 'feb06_sales', sum(feb06.sale_$) as 'feb06_$' from (select * from sales where date >= 1/1/2006 and date <= 1/31/06) as jan06 full outer join (select * from sales where date >= 2/1/2006 and date <= 2/28/06) as feb06 on jan06.salesperson = feb06.salesperson group by jan06.salesperson, feb06.salesperson
This gives me the proper output for everyone except for bob (or anyone else who would have multiple sales in multiple months), who shows up as having 6 sales in both months and equally inflated $ numbers. I'm guessing that 3 jan sales multiplied by 2 feb sales is 6 (so my join is giving me a cross-product...I should've known, eh?). How do I get around this? Am I joining on the wrong field? Grouping incorrectly? Using the wrong type of join?While I realize that I could run a procedure to poop this out, it would be much better to do it with a query. This will go into an asp page (yes, through an ADO connection to SQL Server 2005) and I'd rather hit the database with one query that I can spit out (the above query currently returns in under a second) instead of picking a sales guys and loading variables with his monthly data...and hitting the database many times in the process, only to move on to all the other sales guys one by one.Let me know if you've got a solution! Thanks in advance!