Search code examples
sqlsql-serverselecttemp-tables

Create a temp table with a distinct name and sum of values


I have a table of costs per employee. The table can have multiple rows for a given employee and in each row a distinct cost. I want to end up with a temp table that has the total costs for each employee. So:

Name | Cost
Dave | 563.22
John | 264.00

I tried the following but the below is invalid for updating the cost. What do I have wrong? And is there a better way to do this.

declare @temp2  table
(
name text,
cost integer
)
insert @temp2(name) SELECT DISTINCT ename6 from dbo.condensed7day_query_result

UPDATE t  
SET t.cost = sum(dbo.condensed7day_query_result.cost)
FROM dbo.condensed7day_query_result
 WHERE dbo.condensed7day_query_result.ename6 = t.name)
FROM  @temp2 t

select * from @temp2

Solution

  • Don't use the text data type. Use varchar(). But the answer to your question is an aggregation query:

    insert @temp2(name, cost) 
        select ename6, sum(dqr.cost)
        from dbo.condensed7day_query_result dqr
        group by dqr.ename6;