w3resource

AdventureWorks Database: Compare year-to-date sales between employees

SQL Query - AdventureWorks: Exercise-105 with Solution

105. From the following table write a query in SQL to compare year-to-date sales between employees. Return TerritoryName, BusinessEntityID, SalesYTD, and sales of previous year i.e.PrevRepSales. Sort the result set in ascending order on territory name.

Sample table: Sales.vSalesPerson


Click to view Full table

Sample Solution:

SELECT TerritoryName, BusinessEntityID, SalesYTD,   
       LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales  
FROM Sales.vSalesPerson  
WHERE TerritoryName IN ('Northwest', 'Canada')   
ORDER BY TerritoryName;

Sample Output:

territoryname|businessentityid|salesytd    |prevrepsales|
-------------+----------------+------------+------------+
Canada       |             282|2604540.7172|           0|
Canada       |             278|1453719.4653|2604540.7172|
Northwest    |             284|1576562.1966|           0|
Northwest    |             283|1573012.9383|1576562.1966|
Northwest    |             280|1352577.1325|1573012.9383|

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: return the difference in sales quotas for a specific employee over previous years.
Next: Fetch hiredate of last employee in a department for a salary.


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

SQL: Tips of the Day

Convert Timestamp to date in MySQL Query:

DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'

Database: MySQL

Ref : https://bit.ly/3EJPnMQ