-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlead_lag_example.sql
More file actions
78 lines (72 loc) · 1.31 KB
/
lead_lag_example.sql
File metadata and controls
78 lines (72 loc) · 1.31 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
-- This query works, but we can save a lot of code using LEAD and LAG functions
SELECT
t.EmployeeName
, t.ShiftName
, t.ShiftDate
, (
SELECT TOP 1
ShiftDate
FROM EmployeeShift AS tlead
WHERE
tlead.EmployeeName = t.EmployeeName
AND t.ShiftName = tlead.ShiftName
AND tlead.ShiftDate > t.ShiftDate
ORDER BY
ShiftDate
) AS NextShift
FROM
EmployeeShift AS t
WHERE
t.ShiftName = 'Night'
AND t.ShiftDate = '2015-03-01'
ORDER BY
t.EmployeeName ASC;
-- Example of how to use LEAD and LAG functions at the same time.
WITH Shifts
AS
(
SELECT
EmployeeName
, ShiftName
, ShiftDate
, LEAD(ShiftDate,1) OVER(PARTITION BY EmployeeName, ShiftName ORDER BY ShiftDate asc) NextNightShift
, ROW_NUMBER() OVER(PARTITION BY EmployeeName, ShiftName ORDER BY ShiftDate asc) RowNum
FROM
dbo.EmployeeShift
)
SELECT
EmployeeName
, ShiftName
, ShiftDate
, NextNightShift
FROM
Shifts
WHERE
RowNum = 1
AND ShiftName = 'Night'
AND ShiftDate = '2015-03-01'
ORDER BY
EmployeeName ASC;
-- Using LAG
WITH Shifts
AS
(
SELECT
EmployeeName
, ShiftName
, ShiftDate
, LAG(ShiftName,1) OVER(PARTITION BY employeename ORDER BY ShiftDate desc) PreviousShift
FROM
dbo.EmployeeShift
)
SELECT
EmployeeName
, ShiftName
, ShiftDate
, PreviousShift
FROM
Shifts
WHERE
ShiftDate = '2015-03-24'
ORDER BY
EmployeeName ASC