AdventureWorks Database: Return the difference in sales quotas for a specific employee
SQL Query - AdventureWorks: Exercise-181 with Solution
181. From the following table write a query in SQL to return the difference in sales quotas for a specific employee over previous calendar quarters. Sort the results by salesperson with businessentity id 277 and quotadate year 2012 or 2013.
Sample table: sales.salespersonquotahistory
Sample Solution:
SELECT quotadate AS Year, date_part('quarter',quotadate) AS Quarter, SalesQuota AS SalesQuota,
LAG(SalesQuota) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS PrevQuota,
SalesQuota - LAG(SalesQuota) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS Diff
FROM sales.salespersonquotahistory
WHERE businessentityid = 277 AND date_part('year',quotadate) IN (2012, 2013)
ORDER BY date_part('year',quotadate), date_part('quarter',quotadate);
Sample Output:
year |quarter|salesquota|prevquota|diff | -----------------------+-------+----------+---------+-------+ 2012-02-29 00:00:00.000| 1.0| 952000| | | 2012-05-30 00:00:00.000| 2.0| 1600000| 952000| 648000| 2012-08-30 00:00:00.000| 3.0| 1352000| 1600000|-248000| 2012-11-30 00:00:00.000| 4.0| 839000| 1352000|-513000| 2013-02-28 00:00:00.000| 1.0| 1369000| 839000| 530000| 2013-05-30 00:00:00.000| 2.0| 1171000| 1369000|-198000| 2013-08-30 00:00:00.000| 3.0| 971000| 1171000|-200000| 2013-11-30 00:00:00.000| 4.0| 714000| 971000|-257000|
SQL AdventureWorks Editor:
Practice Online
Contribute your code and comments through Disqus.
Previous: Return only rows that have a count of employees by title.
Next: Return a truncated date with 4 months added to the orderdate.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
SQL: Tips of the Day
ROW_NUMBER() in MySQL
SELECT t0.col3 FROM table AS t0 LEFT JOIN table AS t1 ON t0.col1=t1.col1 AND t0.col2=t1.col2 AND t1.col3>t0.col3 WHERE t1.col1 IS NULL;
Ref : https://bit.ly/3VX3Jzv
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises