Skip to content

Commit

Permalink
Windows Function - Lead() and Lag()
Browse files Browse the repository at this point in the history
  • Loading branch information
ptyadana committed Jan 19, 2021
1 parent 9d3a703 commit 1c57927
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/******** Commonly Used Functions for Time Series ***********/

/* we will assume last digit of server_id is department id */
CREATE VIEW time_series.vw_utilization AS(
SELECT *, server_id % 10 AS dept_id
FROM time_series.utilization
);

SELECT * FROM time_series.vw_utilization
LIMIT 5;



--------------------- LEAD() function ---------------------------
-- LEAD() looks forwards and allows us to compare condition with the next nth row of current row.
-- we can also put offset of how many next rows we want to get.

-- next 1 row
SELECT dept_id, server_id, cpu_utilization,
LEAD(cpu_utilization) OVER (PARTITION BY dept_id ORDER BY cpu_utilization DESC)
FROM time_series.vw_utilization
WHERE event_time BETWEEN '2019-03-05' AND '2019-03-06';

-- next 3 row
SELECT dept_id, server_id, cpu_utilization,
LEAD(cpu_utilization, 3) OVER (PARTITION BY dept_id ORDER BY cpu_utilization DESC)
FROM time_series.vw_utilization
WHERE event_time BETWEEN '2019-03-05' AND '2019-03-06';
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/******** Commonly Used Functions for Time Series ***********/

--------------------- LAG() function ---------------------------
-- to reference rows relative to the currently processed rows.
-- LAG() looks backwards and allows us to compare condition with the previous nth row of current row.

SELECT dept_id, server_id, cpu_utilization,
LAG(cpu_utilization) OVER (PARTITION BY dept_id ORDER BY cpu_utilization DESC)
FROM time_series.vw_utilization
WHERE event_time BETWEEN '2019-03-05' AND '2019-03-06';


-- with offset of 10, looking backwards to previous 10th row from the current one
SELECT dept_id, server_id, cpu_utilization,
LAG(cpu_utilization, 10) OVER (PARTITION BY dept_id ORDER BY cpu_utilization DESC)
FROM time_series.vw_utilization
WHERE event_time BETWEEN '2019-03-05' AND '2019-03-06';

0 comments on commit 1c57927

Please sign in to comment.