Which Transact-SQL query should you use?

A table named Profits stores the total profit made each year within a territory. The Profits table hascolumns
named Territory, Year, and Profit. You need to create a report that displays the profits made by each territory
for each year and its preceding year. Which Transact-SQL query should you use?

A table named Profits stores the total profit made each year within a territory. The Profits table hascolumns
named Territory, Year, and Profit. You need to create a report that displays the profits made by each territory
for each year and its preceding year. Which Transact-SQL query should you use?

A.
SELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER(PARTITION BY Year ORDER BYTerritory) AS NextProfit
FROM Profits

B.
SELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER(PARTITION BY Territory ORDER BY Year) AS NextProfit
FROM Profits

C.
SELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER(PARTITION BY Territory ORDER BY Year) AS NextProfit
FROM Profits

D.
SELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER(PARTITION BY Year ORDER BY Territory) AS NextProfit
FROM Profits

Explanation:
Verified answer as correct.
Reference: http://msdn.microsoft.com/en-us/library/hh231256.aspx
Reference: http://msdn.microsoft.com/en-us/library/hh213125.aspx



Leave a Reply 9

Your email address will not be published. Required fields are marked *


ramunas

ramunas

Answer is C

tomazzi

tomazzi

Answer is B. Preceding year for 2014 is 2013 so you use LAG

Ehab

Ehab

Answer is C becuase of the alias “NextProfit”

dennis

dennis

Interesting 🙂 Ehab has a point.

Umar Memon

Umar Memon

🙂 he is very skilled

cyndi

cyndi

preceding year = the year before, so B is the correct one

Kevin

Kevin

the answer is B,
because it’s ‘order by year’,
it was ascending!!!!!!
the data will be like this:
2012
2013
2014
2015
so you need use lag function!!!

ST

ST

B ( lag will get you previous record, and it is ordered asc)