PARTITION BY multiple columns
The PARTITION BY
clause can be used to break out window averages by multiple data points (columns). You can even calculate the information you want to use to partition your data! For example, you can calculate average goals scored by season and by country, or by the calendar year (taken from the date column).
In this exercise, you will calculate the average number home and away goals scored Legia Warszawa, and their opponents, partitioned by the month in each season.
This is a part of the course
“Data Manipulation in SQL”
Exercise instructions
- Construct two window functions partitioning the average of home and away goals by season and month.
- Filter the dataset by Legia Warszawa's team ID (
8673
) so that the window calculation only includes matches involving them.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
SELECT
date,
season,
home_goal,
away_goal,
CASE WHEN hometeam_id = 8673 THEN 'home'
ELSE 'away' END AS warsaw_location,
-- Calculate average goals partitioned by season and month
___(home_goal) ___(___ ___ ___,
EXTRACT(___ FROM date)) AS season_mo_home,
___(away_goal) ___(___ ___ ___,
EXTRACT(___ FROM date)) AS season_mo_away
FROM match
WHERE
hometeam_id = ___
OR awayteam_id = ___
ORDER BY (home_goal + away_goal) DESC;
This exercise is part of the course
Data Manipulation in SQL
Master the complex SQL queries necessary to answer a wide variety of data science questions and prepare robust data sets for analysis in PostgreSQL.
You will learn about window functions and how to pass aggregate functions along a dataset. You will also learn how to calculate running totals and partitioned averages.
Exercise 1: It's OVERExercise 2: The match is OVERExercise 3: What's OVER here?Exercise 4: Flip OVER your resultsExercise 5: OVER with a PARTITIONExercise 6: PARTITION BY a columnExercise 7: PARTITION BY multiple columnsExercise 8: Sliding windowsExercise 9: Slide to the leftExercise 10: Slide to the rightExercise 11: Bringing it all togetherExercise 12: Setting up the home team CTEExercise 13: Setting up the away team CTEExercise 14: Putting the CTEs togetherExercise 15: Add a window functionWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.