CREATE PROCEDURE Top300Customers AS /* Get Prior Year Customer Totals */ IF EXISTS(Select OBJECT_ID('[tempdb].[dbo].[TempPriorSales]')) BEGIN DROP TABLE TempPriorSales END /* Get Prior Year Customer Totals */ Select IDENTITY(INT, 1, 1) as PriorYearRank, PriorSales.CustomerNumber, PriorSales.CustomerName, PriorSales.PriorSales, PriorYearByMonth.PriorYearMonthlySales INTO #TempPriorSales From ( Select CustomerNumber, CustomerName, SUM(SalesAmountUSDollars) PriorSales From slsMain Where InvoiceDate >= '01/01/2003' and InvoiceDate < '01/01/2004' Group By CustomerNumber, CustomerName ) PriorSales LEFT OUTER JOIN ( Select CustomerNumber, CustomerName, SUM(SalesAmountUSDollars) PriorYearMonthlySales From slsMain Where InvoiceDate >= '09/01/2003' and InvoiceDate < '10/01/2003' Group By CustomerNumber, CustomerName ) PriorYearByMonth ON PriorSales.CustomerNumber = PriorYearByMonth.CustomerNumber and PriorSales.CustomerName = PriorYearByMonth.CustomerName Order By PriorSales.PriorSales DESC DECLARE @CurrentYearTotal NUMERIC(18,2), @PriorYearTotal NUMERIC(18,2) /* Get Current Year's Total Sales */ Select @CurrentYearTotal = SUM(SalesAmountUSDollars) From slsMain Where InvoiceDate >= '01/01/2004' and InvoiceDate <= '12/31/2004' /* Get Prior Year's Total Sales */ Select @PriorYearTotal = SUM(SalesAmountUSDollars) From slsMain Where InvoiceDate >= '01/01/2003' and InvoiceDate <= '12/31/2003' /* Get Current Year Customer Totals and Join with Prior Year Customer Totals. Add Current Total Sales and Prior Total Sales */ Select CurrentSales.CustomerNumber, CurrentSales.CustomerName, CurrentSales.CurrentSales, CurrentYearByMonth.CurrentYearMonthlySales, @CurrentYearTotal AS CurrentTotalSales, #TempPriorSales.PriorYearRank, #TempPriorSales.PriorSales, #TempPriorSales.PriorYearMonthlySales, @PriorYearTotal AS PriorTotalSales From ( Select TOP 300 CustomerNumber, CustomerName, SUM(SalesAmountUSDollars) CurrentSales From slsMain Where InvoiceDate >= '01/01/2004' Group By CustomerNumber, CustomerName Order By SUM(SalesAmountUSDollars) DESC ) CurrentSales LEFT OUTER JOIN ( Select CustomerNumber, CustomerName, SUM(SalesAmountUSDollars) CurrentYearMonthlySales From slsMain Where InvoiceDate >= '09/01/2004' Group By CustomerNumber, CustomerName ) CurrentYearByMonth ON CurrentSales.CustomerNumber = CurrentYearByMonth.CustomerNumber and CurrentSales.CustomerName = CurrentYearByMonth.CustomerName LEFT OUTER JOIN #TempPriorSales ON CurrentSales.CustomerNumber = TempPriorSales.CustomerNumber and CurrentSales.CustomerName = TempPriorSales.CustomerName Order By CurrentSales.CurrentSales DESC /* Drop TempPriorSales Table */ DROP TABLE #TempPriorSales GO