Window Functions

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/11

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

12 Terms

1
New cards

OVER()

Every window function MUST have this, which defines the window of rows used for calculations.

2
New cards

PARTITION BY

Groups Data in a window. Similar to GROUP BY, but does not collapse rows, instead, it resets calculations for each partition

SELECT

region,

date,

revenue,

SUM(revenue) OVER (PARTITION BY region ORDER BY date) AS running_total

FROM sales;

3
New cards

ORDER BY

Defines row order in the window. Just like normal ORDER BY but inside of a window function, it controls how rows are processed within the window

SELECT
 title,
 box_office,
 RANK() OVER (ORDER BY box_office DESC) AS rank
FROM movies;

4
New cards

ROWS BETWEEN

Defines row scope. Controls which rows are included in each calculation

5
New cards

PRECEDING, CURRENT ROW, FOLLOWING

  • (n) PRECEDING —> Includes the last n rows

  • CURRENT ROW —> Includes the row itself

  • (n) FOLLOWING —> Includes the next X rows

SELECT
 date,
 revenue,
 AVG(revenue) OVER (
  ORDER BY date
  ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
 ) AS moving_avg
FROM sales;

6
New cards

UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING

  • UNBOUNDED PRECEDING —> Starts from the first row

  • UNBOUNDED FOLLOWING —> Goes up to the last row

SELECT
 date,
 revenue,
 SUM(revenue) OVER (
  ORDER BY date
  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
 ) AS running_total
FROM sales;

7
New cards

RANGE

Uses value-based ranges. Must include an INTERVAL keyword

SELECT
 date,
 revenue,
 SUM(revenue) OVER (
  ORDER BY date
  RANGE BETWEEN INTERVAL '1 month' PRECEDING AND CURRENT ROW
 ) AS total_sales_this_month
FROM sales;

8
New cards

LAG(column, offset, default) OVER (PARTITION BY… ORDER BY…)

Return the value of a column from a previous row in the result set, based on the ORDER BY clause, without collapsing rows.

  • offset: how many rows behind (default is 1)

  • default: what to return if the lag value doesn’t exist (optional)

9
New cards

LEAD(column, offset, default) OVER (PARTITION BY… ORDER BY…)

Returns the value of a column from a future row in the result set, based on the ORDER BY clause, without collapsing rows

  • offset: how many rows ahead (default is 1)

  • default: value to return if no next row exists (optional)

10
New cards

FIRST_VALUE(column)

Returns the first value in the table or partition

11
New cards

LAST_VALUE(column)

Returns the last value in the table or partition

12
New cards

NTILE(n)

Splits the data into n approximately equal pages