メインコンテンツまでスキップ
バージョン: 26.x

LAG

デスクリプション

LAG()は、セルフ結合を実行せずに前の行のデータにアクセスするウィンドウ関数です。パーティション内で現在の行よりもN行前の行から値を取得します。

Syntax

LAG ( <expr> [, <offset> [, <default> ] ] )

パラメータ

Parameterデスクリプション
expr値を取得する対象の式。サポートされている型:tinyint/smallint/int/bigint/float/double/decimal/string/date/datetime/
offsetオプションのBigint型。先読みする行数。デフォルトは1。
defaultオプション。型は最初のパラメータと同じ。offsetがウィンドウ境界を超えた場合に返される値。デフォルトはNULL。

Return Value

入力式と同じデータ型を返します。

Examples

各営業担当者の現在の売上金額と前日の売上金額の差を計算する:

select stock_symbol, closing_date, closing_price,    
lag(closing_price,1, 0) over (partition by stock_symbol order by closing_date) as "yesterday closing"
from stock_ticker
order by closing_date;
+--------------+---------------------+---------------+-------------------+
| stock_symbol | closing_date | closing_price | yesterday closing |
| ------------ | ------------------- | ------------- | ----------------- |
| JDR | 2014-09-13 00:00:00 | 12.86 | 0 |
| JDR | 2014-09-14 00:00:00 | 12.89 | 12.86 |
| JDR | 2014-09-15 00:00:00 | 12.94 | 12.89 |
| JDR | 2014-09-16 00:00:00 | 12.55 | 12.94 |
| JDR | 2014-09-17 00:00:00 | 14.03 | 12.55 |
| JDR | 2014-09-18 00:00:00 | 14.75 | 14.03 |
| JDR | 2014-09-19 00:00:00 | 13.98 | 14.75 |
+--------------+---------------------+---------------+-------------------+