w3resource

AdventureWorks Database: Return the difference in sales quotas for a specific employee over previous years

SQL Query - AdventureWorks: Exercise-104 with Solution

104. From the following table write a query in SQL to return the difference in sales quotas for a specific employee over previous years. Returun BusinessEntityID, sales year, current quota, and previous quota.

Sample table: Sales.SalesPersonQuotaHistory


Click to view Full table

Sample Solution:

SELECT BusinessEntityID, date_part('year',QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,   
       LAG(SalesQuota, 1,0) OVER (ORDER BY date_part('year',QuotaDate)) AS PreviousQuota  
FROM Sales.SalesPersonQuotaHistory  
WHERE BusinessEntityID = 275 AND date_part('year',QuotaDate) in (2012,2013);

Sample Output:

businessentityid|salesyear|currentquota|previousquota|
----------------+---------+------------+-------------+
             275|   2012.0|      550000|            0|
             275|   2012.0|     1429000|       550000|
             275|   2012.0|     1324000|      1429000|
             275|   2012.0|      729000|      1324000|
             275|   2013.0|     1194000|       729000|
             275|   2013.0|     1575000|      1194000|
             275|   2013.0|     1218000|      1575000|
             275|   2013.0|      849000|      1218000|

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Return the employee with the fewest number of vacation hours.
Next: Compare year-to-date sales between employees.


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