I have a (SQL Server) table similar to the following:
SalesSummary
Year | Team | Person | Person Sales | Team Sales/Yr
2013
Try this.
UPDATE SalesSummary SET TeamSales = (Select Sum(PersonSales)
From SalesSummary S
Where S.Year=SalesSummary.Year AND S.Team=SalesSummary.Team)
I have a table variable instead a regular table, therefore I needed to adapt @Shell's answer a bit - so my solution for the question's problem when the table is a variable:
Update SU
Set TeamSales = (Select Sum(SI.PersonSales)
From @SalesSummary SI
Where SI.Year=SU.Year AND SI.Team=SU.Team)
From @SalesSummary SU
Assuming you are using SQL Server, I think you want something like this:
WITH toupdate AS
(SELECT team, year,
Sum(personsales) OVER (partition BY team, year) AS newTeamSales
FROM salessummary
)
UPDATE toupdate
SET teamsales = newteamsales;
Your original query has several issues and suspicious constructs. First, an aggregation subquery is not updatable. Second, you are doing an aggregation and using a window function with, although allowed, is unusual. Third, you are aggregating by PersonSales
and taking the sum()
. Once again, allowed, but unusual.