Analytic Function LAG/LEAD

About

lag is an analytical function that can be used to get the value of a column in a previous row.

If you want to retrieve the value of the next row, use lead instead of lag.

Because the functions provide access to more than one row of a table at the same time without a self-join, they can enhance processing speed.

Syntax

{LAG | LEAD} ( value_expr [, offset] [, default] ) 
   OVER ( [query_partition_clause] order_by_clause )

The LAG function provides access to a row at a given offset prior to the current position, and the LEAD function provides access to a row at a given offset after the current position.

The [query_partition_clause] give a reliable relative positions of rows.

Example : How to retrieve the quantity sold from the previous month ?

The example schema SH is used.

SELECT CALENDAR_MONTH_DESC, 
       sum(quantity_sold), 
       lag(sum(quantity_sold),1) over (ORDER BY CALENDAR_MONTH_DESC) "Previous Month" 
FROM 
       SH.sales,
       SH.TIMES
WHERE
       SH.times.TIME_ID = SH.sales.TIME_ID AND
       SH.times.CALENDAR_YEAR = '2000'
GROUP BY CALENDAR_MONTH_DESC
ORDER BY CALENDAR_MONTH_DESC ASC

And you get :

CALENDAR_MONTH_DESC SUM(QUANTITY_SOLD) Previous Month
2000-01 44270
2000-02 41218 44270
2000-03 38906 41218
2000-04 34962 38906
2000-05 40092 34962
2000-06 35976 40092
2000-07 37068 35976
2000-08 40738 37068
2000-09 40094 40738
2000-10 43084 40094
2000-11 39418 43084
2000-12 29466 39418

The little problem of this time solution against an ago function for a period-to-period comparison is that you don't have the previous value for the month 2000-01 because the value is not in the returned data set.

  • Bookmark "Analytic Function LAG/LEAD" at del.icio.us
  • Bookmark "Analytic Function LAG/LEAD" at Digg
  • Bookmark "Analytic Function LAG/LEAD" at Ask
  • Bookmark "Analytic Function LAG/LEAD" at Google
  • Bookmark "Analytic Function LAG/LEAD" at StumbleUpon
  • Bookmark "Analytic Function LAG/LEAD" at Technorati
  • Bookmark "Analytic Function LAG/LEAD" at Live Bookmarks
  • Bookmark "Analytic Function LAG/LEAD" at Yahoo! Myweb
  • Bookmark "Analytic Function LAG/LEAD" at Facebook
  • Bookmark "Analytic Function LAG/LEAD" at Yahoo! Bookmarks
  • Bookmark "Analytic Function LAG/LEAD" at Twitter
  • Bookmark "Analytic Function LAG/LEAD" at myAOL
 
analytic/analytic_functions/analytic_function_lag.txt · Last modified: 2009/04/25 22:07 by gerardnico