DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to update year-to-date sales figure?

Execute the following SQL Server T-SQL script in Management Studio Query Editor to demonstrate YTD column update which typically maybe scheduled as a night job in SQL Server Agent.


-- SQL update group by - SQL correlated subquery update
USE AdventureWorks;
UPDATE Sales.SalesPerson
SET    SalesYTD = isnull(
      (SELECT   SUM(so.SubTotal)
         FROM     Sales.SalesOrderHeader AS so
         WHERE    so.OrderDate IN
                       (SELECT OrderDate
                                FROM   Sales.SalesOrderHeader AS soh
                                WHERE  soh.SalesPersonID = so.SalesPersonID
                                          -- AND year(OrderDate) = year(getdate()))
                                          AND year(OrderDate) = 2004)
          AND Sales.SalesPerson.SalesPersonID = so.SalesPersonID
         GROUP BY so.SalesPersonID),0);
 
GO
-- (17 row(s) affected)
 
-- SQL currency formatting - money format
SELECT LastName + ', ' + FirstName            AS SalesPerson,
       '$' + CONVERT(VARCHAR,SalesQuota,1)    AS SalesQuota,
       '$' + CONVERT(VARCHAR,Bonus,1)         AS Bonus,
       '$' + CONVERT(VARCHAR,SalesYTD,1)      AS SalesYTD,
       '$' + CONVERT(VARCHAR,SalesLastYear,1) AS SalesLastYear
FROM   Sales.SalesPerson sp
       INNER JOIN HumanResources.Employee e
         ON sp.SalesPersonID = e.EmployeeID
       INNER JOIN Person.Contact c
         ON e.ContactID = c.ContactID
ORDER BY SalesPerson
GO
/* Partial result
 
SalesPerson             SalesQuota  Bonus       SalesYTD          SalesLastYear
Ansman-Wolfe, Pamela    $250,000.00 $5,000.00   $788,700.12       $1,927,059.18
Blythe, Michael         $300,000.00 $4,100.00   $1,858,626.93     $1,750,406.48
Campbell, David         $250,000.00 $3,500.00   $815,513.35       $1,371,635.32
Carson, Jillian         $250,000.00 $2,500.00   $1,651,313.92     $1,997,186.20

*/

 

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE