SQL How to Update SUM of column over group in same table

前端 未结 3 1029
暖寄归人
暖寄归人 2020-12-18 06:32

I have a (SQL Server) table similar to the following:

SalesSummary

Year | Team | Person | Person Sales | Team Sales/Yr

2013     

3条回答
  •  -上瘾入骨i
    2020-12-18 07:19

    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.

提交回复
热议问题