I'm trying to avoid using a cursor.I have two tables. SemiconWest2004Relevant Fields: AccountNumber IntCompany_Name Varchar(100) and Sales_HistoryRelevant Fields:AccountNumber intPartnumber Varchar(50) Quantity intTotalsaleNet floatI want the following data:AccountNumber & Company NameEach distinct partnumber they boughtThe total number of quantity they purchased of that part - sum(quantity)The total sales of each part - convert(Money, sum(total_salenet))My problem When I join on the accountnumber, because there might be more than one instance of an accountnumber I get sums that are out of whack. The way I currently solved the problem is this but I didn't know if there was a better solution. select accountnumber, max(company_name) as company_nameinto #temp1 from semiconwest2004 where accountnumber is not null group by accountnumberselect a.AccountNumber, max(company_name), Partnumber, sum(Quantity), convert(varchar, convert(money, sum(TotalSaleNet), 50)) as TotalSalesfrom #temp1 a join smc_sales.dbo.sales_history bon a.accountnumber=b.accountnumbergroup by a.accountnumber, Partnumberorder by a.accountnumber
Any suggestions on how to improve are very welcome.