Skip to content

Instantly share code, notes, and snippets.

@doryokujin
Last active November 4, 2016 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doryokujin/b3664aafee0eb757bc66 to your computer and use it in GitHub Desktop.
Save doryokujin/b3664aafee0eb757bc66 to your computer and use it in GitHub Desktop.
SELECT
time, goods_id, amount,
--第2引数で遡るステップ数を指定--
LAG(amount, 1) OVER (PARTITION BY goods_id ORDER BY time) AS lag1,
--第2引数を指定しない時は1つ前のamountを取得--
LAG(amount) OVER (PARTITION BY goods_id ORDER BY time) AS lag2,
--第3引数で存在しない場合のデフォルト値を指定できる--
LAG(amount, 1, 0) OVER (PARTITION BY goods_id ORDER BY time) AS lag3,
--第2引数で先のステップ数を指定--
LEAD(amount, 1) OVER (PARTITION BY goods_id ORDER BY time) AS lead1,
--第2引数を指定しない時は1つ先のamountを取得--
LEAD(amount) OVER (PARTITION BY goods_id ORDER BY time) AS lead2,
--第3引数で存在しない場合のデフォルト値を指定できる--
LEAD(amount, 1, 0) OVER (PARTITION BY goods_id ORDER BY time) AS lead3
FROM sales_slip_10k
ORDER BY goods_id, time
LIMIT 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment