Window Partitions

Data Manipulation in SQL

Mona Khalil

Data Scientist, Greenhouse Software

OVER and PARTITION BY

  • Calculate separate values for different categories
  • Calculate different calculations in the same column
AVG(home_goal) OVER(PARTITION BY season)
Data Manipulation in SQL

Partition your data

  • How many goals were scored in each match, and how did that compare to the overall average?
SELECT
    date,
    (home_goal + away_goal) AS goals,
    AVG(home_goal + away_goal) OVER() AS overall_avg
FROM match;
| date       | goals | overall_avg |
|------------|-------|-------------|
| 2011-12-17 | 3     | 2.73210     |
| 2012-05-01 | 2     | 2.73210     |
| 2012-11-27 | 4     | 2.73210     |
| 2013-04-20 | 1     | 2.73210     |
| 2013-11-09 | 5     | 2.73210     |
Data Manipulation in SQL

Partition your data

  • How many goals were scored in each match, and how did that compare to the season's average?
SELECT
    date,
    (home_goal + away_goal) AS goals,
    AVG(home_goal + away_goal) OVER(PARTITION BY season) AS season_avg
FROM match;
| date       | goals | season_avg  |
|------------|-------|-------------|
| 2011-12-17 | 3     | 2.71646     |
| 2012-05-01 | 2     | 2.71646     |
| 2012-11-27 | 4     | 2.77270     |
| 2013-04-20 | 1     | 2.77270     |
| 2013-11-09 | 5     | 2.76682     |
Data Manipulation in SQL

PARTITION by Multiple Columns

SELECT 
  c.name,
  m.season,
  (home_goal + away_goal) AS goals,
  AVG(home_goal + away_goal) 
      OVER(PARTITION BY m.season, c.name) AS season_ctry_avg
FROM country AS c
LEFT JOIN match AS m 
ON c.id = m.country_id
| name        | season    | goals     | season_ctry_avg |
|-------------|-----------|-----------|-----------------|
| Belgium     | 2011/2012 | 1         | 2.88            |
| Netherlands | 2014/2015 | 1         | 3.08            |
| Belgium     | 2011/2012 | 1         | 2.88            |
| Spain       | 2014/2015 | 2         | 2.66            |
Data Manipulation in SQL

PARTITION BY considerations

  • Can partition data by 1 or more columns
  • Can partition aggregate calculations, ranks, etc
Data Manipulation in SQL

Let's practice!

Data Manipulation in SQL

Preparing Video For Download...