I have two tables
(1) MonthlyTarget {SalesManCode, TargetMonthYear, TargetValue}; this table has 1966177 rows.
(2) MonthlySales {SalesManCode, SaleDate, AchievedValue};
this table has 400310 rows.
I have to make a query that produces a result like the following table:
{SalesManCode, JanTar, JanAch, FebTar, FebAch,....., DecTar, DecAch}
The problem is, joining these two tables taking a long time.
What should be the query?
How can the query be optimized?
I don’t want to consider indexing.
It looks like you’re missing some columns in your MonthlyTarget table, namely a “TargetDate” column.
In addition to what everyone has already said about indexing, sometimes a divide-and-conquer approach can really help. Rather than joining a 1966177 row table to a 400310 row table, create to tiny temp tables and join them together instead:
The queries above create two intermediate tables which should contain the same number of records as your SalesMan table. Joining them is straightforward:
If you find yourself needing to pull out data by month all the time, move the code into a view instead.
PIVOT requires SQL Server 2005 or higher, and its often a very useful operator. Hopefully SQL Server 2008 will allow users to pivot on more than one column at a time, which will result in an even simpler query than shown above.
Using SQL Server 2000:
PIVOT is syntax sugar. For example,
Becomes