Rman Edv
Rman Edv

Reputation: 163

Summing three values of one column and inserting it in another column in SQL Server 2008 R2

I have a table like this :

(ID)---(count)----(SumCount)

I have three rows (three count) for each ID, I want to sum them and insert them in sumCount grouped by their IDs.

My ideal result is one row for each ID and the SumCount for each of them.

Do I have to join the table to itself?

Update Mytable
set sumCount = (select sum(count) as SumCount from Mytable group by ID) 

The problem is: it does not gives just one value and I get the error

Upvotes: 0

Views: 53

Answers (2)

mehdi lotfi
mehdi lotfi

Reputation: 11571

Update Yourtable
set sumCount=z.SumCount
From (select ID, sum(count) as SumCount 
      from Yourtable 
      groub by ID
     )z
where YourTable.Id = Z.ID

Upvotes: 3

Farrokh
Farrokh

Reputation: 1167

i think this worked correctly.
try and response

Update Mytable M1
  set sumCount=(select sum(count) from Mytable M2 WHERE M1.ID=M2.ID)

Upvotes: 1

Related Questions