使用 LAG() 和 LEAD()

SQL Server 中的时间序列分析

Maham Faisal Khan

Senior Data Science Content Developer

LAG() 窗口函数

SELECT
    dsr.CustomerID,
    dsr.MonthStartDate,
    LAG(dsr.NumberOfVisits) OVER (PARTITION BY dsr.CustomerID ORDER BY dsr.MonthStartDate) AS Prior,
    dsr.NumberOfVisits
FROM dbo.DaySpaRollup dsr;
CustomerID MonthStartDate Prior NumberOfVisits
1 2018-12-01 NULL 49
1 2019-01-01 49 117
1 2019-02-01 117 104
SQL Server 中的时间序列分析

LEAD() 窗口函数

SELECT
    dsr.CustomerID,
    dsr.MonthStartDate,
    dsr.NumberOfVisits,
    LEAD(dsr.NumberOfVisits) OVER (PARTITION BY dsr.CustomerID ORDER BY dsr.MonthStartDate) AS Next
FROM dbo.DaySpaRollup dsr;
CustomerID MonthStartDate NumberOfVisits Next
1 2018-12-01 49 117
1 2019-01-01 117 104
1 2019-02-01 104 108
SQL Server 中的时间序列分析

指定回溯的行数

SELECT
   dsr.CustomerID,
   dsr.MonthStartDate,
   LAG(dsr.NumberOfVisits, 2) OVER (PARTITION BY dsr.CustomerID ORDER BY dsr.MonthStartDate) AS Prior2,
   LAG(dsr.NumberOfVisits, 1) OVER (PARTITION BY dsr.CustomerID ORDER BY dsr.MonthStartDate) AS Prior1,
   dsr.NumberOfVisits
FROM dbo.DaySpaRollup dsr;
CustomerID MonthStartDate Prior2 Prior NumberOfVisits
1 2018-12-01 NULL NULL 49
1 2019-01-01 NULL 49 117
1 2019-02-01 49 117 104
SQL Server 中的时间序列分析

窗口与过滤

SELECT
    Date,
    LAG(Val, 1) OVER(ORDER BY DATE) AS PriorVal,
    Val
FROM t;
Date PriorVal Val
2019-01-01 NULL 3
2019-01-02 3 6
2019-01-03 6 4
SELECT
    Date,
    LAG(Val, 1) OVER(ORDER BY DATE) AS PriorVal,
    Val
FROM t
WHERE
    t.Date > '2019-01-02';
Date PriorVal Val
2019-01-03 NULL 4
SQL Server 中的时间序列分析

窗口、过滤与 CTE

WITH records AS (
  SELECT
      Date,
      LAG(Val, 1) OVER(ORDER BY Date) AS PriorVal,
      Val
  FROM t
)
SELECT
    r.Date,
    r.PriorVal,
    r.Val
FROM records r
WHERE
    r.Date > '2019-01-02';
Date PriorVal Val
2019-01-03 6 4
SQL Server 中的时间序列分析

Passons à la pratique !

SQL Server 中的时间序列分析

Preparing Video For Download...