FirebirdSQL logo

LAG Examples

Suppose you have RATE table that stores the exchange rate for each day.To trace the change of the exchange rate over the past five days you can use the following query.

select
  bydate,
  cost,
  cost - lag(cost) over (order by bydate) as change,
  100 * (cost - lag(cost) over (order by bydate)) /
    lag(cost) over (order by bydate) as percent_change
from rate
where bydate between dateadd(-4 day to current_date)
and current_date
order by bydate
Result
bydate     cost   change percent_change
---------- ------ ------ --------------
27.10.2014  31.00 <null>         <null>
28.10.2014  31.53   0.53         1.7096
29.10.2014  31.40  -0.13        -0.4123
30.10.2014  31.67   0.27         0.8598
31.10.2014  32.00   0.33         1.0419

LAST_VALUE()

Last value from the current partition

Result type

The same as type as expr

Syntax
LAST_VALUE ( <expr> ) OVER <window_name_or_spec>
Table 1. Arguments of LAST_VALUE
Argument Description

expr

Expression.May contain a table column, constant, variable, expression, scalar function.Aggregate functions are not allowed as an expression.