Tuesday, April 24, 2012

SQL 2012 LAG and LEAD

New TSQL functions LAG and LEAD are two amaizing features. Lets have look at a data set like below and see how these functions are important


Here it contains sales order details with customer, location, date and amount etc. To obtain the monthly total sales for 2012 follwing query can be used

SELECT MONTH(SODate) MonthOfYear ,SUM(OrderAmount) TotalSales
FROM dbo.SalesOrder
WHERE YEAR(SODATE) = 2012
GROUP BY MONTH(SODate)
ORDER BY MONTH(SODate)

So the results set will be like this


Now in each row we need to show total sales for the prevous month and the next month. In prevous versions of SQL server we need to join above results set again to obtain this results. But with the new two features LAG and LEAD this can be achived easily. Below is the query used.

SELECT MONTH(SODate) MonthOfYear ,SUM(OrderAmount) TotalSales
,LAG(SUM(OrderAmount),1) OVER( ORDER BY MONTH(SODate) ) PreviousMonth
,LEAD(SUM(OrderAmount),1) OVER( ORDER BY MONTH(SODate) ) NextMonth

FROM dbo.SalesOrder
WHERE YEAR(SODATE) = 2012
GROUP BY MONTH(SODate)
ORDER BY MONTH(SODate)

And the reslts set will be like this.

No comments:

Post a Comment