Skip to content Skip to sidebar Skip to footer

Merge Multiple Records Into One Row In A Table

I have a table which has multiple records of the same sales agent id but different sales amount. How can I delete the multiple rows and just have the aggregate of the total value.

Solution 1:

SELECT SalesAgentId, SalesAgentName, SUM(SalesAmount) AS SalesAmount
  INTO #AggSales
  FROM Sales
 GROUP BY SalesAgentId, SalesAgentName;

TRUNCATE TABLE Sales;    

INSERT INTO Sales
SELECT * FROM #AggSales;

DROP TABLE #AggSales;

Solution 2:

This is the easiest way I can think of doing it:

create table #tempSales (salesagentid int, salesagentname varchar(50), salesamount money)
go

insert into #tempSales 
select salesagentid, salesagentname, sum(salesamount)
from salesTable
group by salesagentid, salesagentname
go

select *
from #tempSales

Solution 3:

SELECT SalesAgentID, SUM(SalesAmount) FROM Sales GROUPBY SalesAgentID

But there's something wrong here... Why your table have BOTH SalesAgentId and SalesAgentName?

It should contain only the ID, the name should be in a SalesAgent table. Then you would retrieve the name with a join


Post a Comment for "Merge Multiple Records Into One Row In A Table"