MS SQL Server を使うようになったのでメモ。
サンプルデータの WideWorldImportersDW スキーマを使って T-SQL を覚える。
Fact.Sale と Dimension.Date を使ってから月間受注累計を抽出するクエリ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | DECLARE @end_date date ; SELECT @end_date = EOMONTH( '2013-02-01' ); with t1 as ( SELECT s.[Invoice Date Key ] as sale_date, d.[Calendar Month Label] as sale_month, sum (s.[Total Including Tax]) as total_sale FROM [WideWorldImportersDW].[Fact].[Sale] as s inner join [Dimension].[ Date ] as d on s.[Invoice Date Key ] = d.[ Date ] where s.[Invoice Date Key ] between '2013-01-01' and @end_date group by s.[Invoice Date Key ], d.[Calendar Month Label] ) select t1.[sale_date], t1.[sale_month], t1.[total_sale], sum (t1.[total_sale]) over( partition by t1.[sale_month] order by t1.[sale_date] rows unbounded preceding ) as agg_sale from t1 order by t1.[sale_date]; |
結果はこうなる。

月間受注累計を抽出
EOMONTH 関数で月末の日付取得出来るの便利。
PowerBI で表示するとこうなる。

PowerBI で日別受注と当月累計を表示
参考図書
ビッグデータ分析・活用のためのSQLレシピ
SQL Server 2016の教科書 開発編