SQL How to update SUM of a column by group in one table

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

Salesumummary

Year | Team | Man | Sales staff | Team sales / year

2013 Jim $ 10 ??

2013 1 Anna $ 0 ??

2013 2 John $ 8 ??

2013 3 Todd $ 4 ??

2013 3 Alan $ 1 ??

2014 3 Alan $ 22 ??

I am trying to summarize this example SalesSummary table and insert the corresponding values ​​into the Sales Sales column. In this example, I would like to get $ 10 in the 1st and 2nd columns, $ 8 in the 3rd, $ 5 in the 4th and 5th and 22 dollars in the slot of the 6th column. Forgive my ignorance of SQL, but I settled on what I was told this is a bad solution as follows:

UPDATE SalesSummary SET TeamSales = sum.TeamSales
FROM (SELECT Team, Year, SUM(PersonSales) OVER (Partition By Team, Year) as TeamSales)
      FROM SalesSummary
      GROUP BY Team, Year, PersonSales
     ) AS sum, SalesSummary as SS
WHERE sum.Team = ss.Team AND sum.Year = ss.Year

I was hoping someone would be able to show how best to perform this type of update. I appreciate any help, advice or examples. Sorry if this is obvious.

+4
source share
2 answers

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; 

. -, . -, , , , . -, PersonSales sum(). , , .

+9

.

UPDATE  SalesSummary SET TeamSales = (Select Sum(PersonSales) 
        From    SalesSummary S 
        Where S.Year=SalesSummary.Year AND S.Team=SalesSummary.Team)
+5

Source: https://habr.com/ru/post/1527639/


All Articles