Skip to content

Instantly share code, notes, and snippets.

@ritalin
Last active January 8, 2024 09:24
Show Gist options
  • Save ritalin/2cda493ce65466789e7df33e1c615eea to your computer and use it in GitHub Desktop.
Save ritalin/2cda493ce65466789e7df33e1c615eea to your computer and use it in GitHub Desktop.
LeetCode SQL question #1321
SQLで移動累計と移動平均を求める良問題
https://leetcode.com/problems/restaurant-growth/
Customer table:
+-------------+--------------+--------------+-------------+
| customer_id | name | visited_on | amount |
+-------------+--------------+--------------+-------------+
| 1 | Jhon | 2019-01-01 | 100 |
| 2 | Daniel | 2019-01-02 | 110 |
| 3 | Jade | 2019-01-03 | 120 |
| 4 | Khaled | 2019-01-04 | 130 |
| 5 | Winston | 2019-01-05 | 110 |
| 6 | Elvis | 2019-01-06 | 140 |
| 7 | Anna | 2019-01-07 | 150 |
| 8 | Maria | 2019-01-08 | 80 |
| 9 | Jaze | 2019-01-09 | 110 |
| 1 | Jhon | 2019-01-10 | 130 |
| 3 | Jade | 2019-01-10 | 150 |
+-------------+--------------+--------------+-------------+
ただし、開始日はデータの期間内に存在しなければならない(たとえ売り上げがなくても)
例えば、2019-01-06は2018-12-31が存在しないため、結果から刈られなければならない
上記ケースでは、2019-01-07~2019-01-10についての過去7日の集計を行う問題
Windowフレームを駆使することでよりスマートなSQLとなる
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment