I need to create a sales & commission report
Basically it goes (please forgive the blatent craziness of the SaleDate table, but I'm simplifying the business logic, and in reality it actually makes sense to have it this way)
SELECT agentName,
SUM(sales.Amount) AS Gross,
SUM(sales.Amount * sales.Commission) AS Commission
FROM agent
INNER JOIN sales ON agent.agentId = sales.agentId
WHERE sales.saleId IN (SELECT saleId FROM saleDate WHERE saleDate.myDate BETWEEN @minDate AND @maxDate)
GROUP BY agentName
So this query works absolutely fine. The problem occurs when I need to add a second date range.
IE, where they want to compare 2007 sales & 2008 sales side by side.
I currently have basically the same query, but I've added aliases to the sales table and added another one
SELECT agentName,
SUM(sales1.Amount) AS Gross1,
SUM(sales1.Amount * sales1.Commission) AS Commission1,
SUM(sales2.Amount) AS Gross2,
SUM(sales2.Amount * sales2.Commission) AS Commission2,
SUM(sales3.Amount) AS Gross3,
SUM(sales3.Amount * sales3.Commission) AS Commission3
FROM agent
INNER JOIN sales1 ON agent.agentId = sales1.agentId
INNER JOIN sales2 ON agent.agentId = sales2.agentId
INNER JOIN sales3 ON agent.agentId = sales3.agentId
WHERE sales1.saleId IN (SELECT saleId FROM saleDate WHERE saleDate.myDate BETWEEN @minDate1 AND @maxDate1) OR
sales2.saleId IN (SELECT saleId FROM saleDate WHERE saleDate.myDate BETWEEN @minDate2 AND @maxDate2) OR
sales3.saleId IN (SELECT saleId FROM saleDate WHERE saleDate.myDate BETWEEN @minDate3 AND @maxDate3)
GROUP BY agentName
This query however is taking forever (over 20 minutes before I cancelled it), the original took less than a second and if I only use two groups it takes 9 seconds.
Any ideas on how to improve this performance?
I'm willing to change the design of this query.