注:テストデータベースのバージョンはMySQL8.0です。
scottユーザーがテーブルを作成してデータステートメントを入力する必要がある場合は、以下を参照してください:
scott createtablesおよびenterdatasqlスクリプト
1.需要
モバイル集計を計算します。
たとえば、テーブルEMPで賃金の移動合計を見つけるには、最初の従業員の雇用日から開始し、任意の90日間の合計を計算して、最初の従業員から最後の従業員までの90日間の費用の変動を観察します。
次の結果セットが返されます。
2.解決策
この問題は、window関数の節で移動可能なウィンドウを指定することで簡単に解決できます。
重要なのは、ウィンドウ関数で採用日で並べ替えてから、最初に採用された従業員から始まる90日間のウィンドウを指定することです。
このようなウィンドウ関数を使用できない場合は、スカラーサブクエリを使用できます。これにより、ソリューションがより複雑になる可能性があります。
-- 标量子查询写法
select e.hiredate,
e.sal,
(select sum(sal) from emp d
where d.hiredate between e.hiredate - 90 and e.hiredate) as spending_pattern
from emp e
order by 1;
テスト記録:
mysql> select e.hiredate,
-> e.sal,
-> (select sum(sal) from emp d
-> where d.hiredate between e.hiredate - 90 and e.hiredate) as spending_pattern
-> from emp e
-> order by 1;
+------------+---------+------------------+
| hiredate | sal | spending_pattern |
+------------+---------+------------------+
| 1980-12-17 | 800.00 | 800.00 |
| 1981-02-20 | 1600.00 | 1600.00 |
| 1981-02-22 | 1250.00 | 2850.00 |
| 1981-04-02 | 2975.00 | 2975.00 |
| 1981-05-01 | 2850.00 | 2850.00 |
| 1981-06-09 | 2450.00 | 2450.00 |
| 1981-09-08 | 1500.00 | 1500.00 |
| 1981-09-28 | 1250.00 | 2750.00 |
| 1981-11-17 | 5000.00 | 5000.00 |
| 1981-12-03 | 950.00 | 8950.00 |
| 1981-12-03 | 3000.00 | 8950.00 |
| 1982-01-23 | 1300.00 | 1300.00 |
| 1987-06-13 | 3000.00 | 4100.00 |
| 1987-06-13 | 1100.00 | 4100.00 |
+------------+---------+------------------+
14 rows in set (0.00 sec)