0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LAG関数(備忘録)

Posted at

1.LAG関数の特徴

LAG関数とは、ウィンドウ関数と呼ばれている
ある日の前日の売上などを同じ行に追加して、比較できるようになります。

今回の場合は、トランザクションデータを使っており、日々蓄積されるデータになっております。

2.記述の手順

まずは、
GROUP BYを使って、日の集計を行います。
その後に、 LAG関数で前日のデータを取得してくるのですが、
その前に、データを並び替える必要があります。
OVERとORDER BYを使ってどの値でソートするのかを決めます。
今回の場合は、日付で一個前のデータがほしいので、ORDER BYには
sales_ymdにします。

3日前までのデータを取得したいので、LAGの値を1〜3で用意します。

記述したコードがこちら

WITH sales_total_day AS (
SELECT
sales_ymd,
sum(amount) amount
FROM
`100_knock.receipt`
GROUP BY
sales_ymd
)

SELECT
sales_ymd,
amount ,
LAG(sales_ymd ,1) OVER(ORDER BY sales_ymd) sales_ymd_1agoa,
LAG(amount ,1) OVER(ORDER BY sales_ymd) amount_1ago,
LAG(sales_ymd ,2) OVER(ORDER BY sales_ymd) sales_ymd_2ago,
LAG(amount ,2) OVER(ORDER BY sales_ymd) amount_2ago,
LAG(sales_ymd ,3) OVER(ORDER BY sales_ymd) sales_ymd_3ago,
LAG(amount ,3) OVER(ORDER BY sales_ymd) amount_3ago
FROM
sales_total_day
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?