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

流过昼夜 提交于 2019-12-25 09:29:04

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/44741835/create-a-temp-table-with-a-distinct-name-and-sum-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!