I'm building a stored proc that pulls a lot of different data from several different tables, and I need a way to pull sales information from a sales table and then perform various summations on that sales data. In the example below I accomplish this using a temp table, but someone suggested there's probably a better way. Is there a more efficient way to accomplish what I'm doing here?
SELECT * INTO #TempSales FROM [Sales] WHERE ClientId = @ClientId
SELECT
[Customer].[CustomerID],
[Customer].[AccountBalAmountOpen],
[Customer].[AccountAgeAmountDays0],
[Customer].[AccountAgeAmountDays30],
[Customer].[AccountAgeAmountDays60],
[Customer].[AccountAgeAmountDays90],
[Customer].[AccountAgeAmountDaysOver90],
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 385) AS ServiceLifeTimeSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 385 AND MONTH(SaleDate) = MONTH(GETDATE()) AND YEAR(SaleDate) = YEAR(GETDATE())) AS ServiceMonthToDateSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 385 AND YEAR(SaleDate) = YEAR(GETDATE())) AS ServiceYearToDateSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 385 AND YEAR(SaleDate) = (YEAR(GETDATE()) - 1)) AS ServicePreviousYearSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 460) AS PartsLifeTimeSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 460 AND MONTH(SaleDate) = MONTH(GETDATE()) AND YEAR(SaleDate) = YEAR(GETDATE())) AS PartsMonthToDateSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 460 AND YEAR(SaleDate) = YEAR(GETDATE())) AS PartsYearToDateSales,
(SELECT SUM(SalesAmount) FROM #TempSales WHERE CustomerId = [Customer].[CustomerID] AND Origin = 460 AND YEAR(SaleDate) = (YEAR(GETDATE()) - 1)) AS PartsPreviousYearSales,
[Orders].[CustomerId] AS ParentCustomerId,
[Orders].[OrderId],
[Orders].[OrderStatus],
[Orders].[UnitId],
[Orders].[FleetId],
[Orders].[CreatedDate] AS OrderCreatedDate,
[Orders].[OrderType],
[OrderParts].[OrderId] AS ParentOrderId,
[OrderParts].[PartId],
[OrderParts].[PartDescription],
[OrderParts].[QuantityShip],
[OrderParts].[QuantityBackOrder],
[OrderParts].[CreatedDate] AS PartCreatedDate
FROM [Customer]
LEFT JOIN [Orders]
ON [Orders].[CustomerId] = [Customer].[CustomerID]
LEFT JOIN [OrderParts]
ON [OrderParts].[OrderId] = [Orders].[OrderId]
WHERE [Customer].[ClientID] = @ClientId
DROP TABLE #TempSales