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

前端 未结 3 1019
暖寄归人
暖寄归人 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条回答
  • 2020-12-18 06:54

    Try this.

    UPDATE  SalesSummary SET TeamSales = (Select Sum(PersonSales) 
            From    SalesSummary S 
            Where S.Year=SalesSummary.Year AND S.Team=SalesSummary.Team)
    
    0 讨论(0)
  • 2020-12-18 07:18

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题