SQLUSA

Microsoft SQL Server 2008 Best Practices

How to update a table with group by sum?

 

Execute the following script in Query Editor to update the SalesPerson table with a correlated GROUP BY subquery:

USE AdventureWorks2008;

GO

 

UPDATE sp

SET SalesYTD = SalesYTD +

    (SELECT SUM(soh1.SubTotal)

     FROM Sales.SalesOrderHeader AS soh1

     WHERE soh1.OrderDate =

     (SELECT MAX(OrderDate)

      FROM Sales.SalesOrderHeader AS soh2

      WHERE soh2.SalesPersonID = soh1.SalesPersonID)

      AND sp.BusinessEntityID = soh1.SalesPersonID

      GROUP BY soh1.SalesPersonID)

FROM Sales.SalesPerson sp

WHERE Bonus >= $4000;

GO

 

 

 

SQLUSA - The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page