Window Functions

studied byStudied by 0 people
0.0(0)
learn
LearnA personalized and smart learning plan
exam
Practice TestTake a test on your terms and definitions
spaced repetition
Spaced RepetitionScientifically backed study method
heart puzzle
Matching GameHow quick can you match all your cards?
flashcards
FlashcardsStudy terms and definitions

1 / 6

encourage image

There's no tags or description

Looks like no one added any tags here yet for you.

7 Terms

1

OVER()

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

New cards
2

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;

New cards
3

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;

New cards
4

ROWS BETWEEN

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

New cards
5

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;

New cards
6

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;

New cards
7

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;

New cards
robot