Wednesday, April 3, 2013

T-SQL 2012: LAG & LEAD

I’ve just started playing with SQL 2012 and wanted to show you the new LAG and LEAD features.

I’ll use the report below as an example. Suppose you needed to generate a report that showed the last three years of sales. The result set would need to look something like this:

Lag and Lead

LEAD looks ahead the specified number of rows from the current row, and LAG (you guessed it!) looks behind the specified number of rows from the current row. By using the OVER clause you can specify your grouping (partitioning) and sort order.

Using SQL 2012 you can easily accomplish this using the following SELECT statement:

SELECT
   year(docdate)  AS ‘Order Year’
  ,SUM(SubTotal) AS ‘Current Yr Sales’
  ,LAG(SUM(SubTotal), 1, 0) OVER (ORDER BY YEAR(docdate)) AS ‘Last Year Sales’
  ,LAG(SUM(SubTotal), 2, 0) OVER (ORDER BY YEAR(docdate)) AS ‘Year Before Last’
  ,LAG(SUM(SubTotal), 3, 0) OVER (ORDER BY YEAR(docdate)) AS ‘Three Years Ago’
  ,LEAD(SUM(SubTotal), 1, 0) OVER (ORDER BY YEAR(docdate)) AS ‘Next Year’
FROM SOP30200
GROUP BY YEAR(DOCDATE)
ORDER BY YEAR(DOCDATE);

Have fun with it!

Until next post!

Leslie

No comments: