Applying SQL Aggregate Functions to Soccer Data
Quick Recap
Great job on making it this far! Thus far, we've covered a great deal, from drilling into COUNT and DISTINCT to exploring SUM and GROUP BY. These are some of the key SQL functions required to dig deep into any dataset. In this unit, we're going to broaden our repertoire by applying these aggregate functions to analyze data related to Lionel Messi's career achievements.
As you may recall from our previous lessons, aggregate functions allow us to perform calculations on a set of values to return a single scalar value. We've already seen the COUNT and SUM functions in action, but have you ever wondered if we could derive other useful insights, such as averages? That’s where the SQL AVG function comes into play.
SUM and AVG Functions
At this juncture, the SUM function must seem pretty familiar to you. It does the heavy lifting when we need to find total values. For instance, it calculates total trophies won or total goals scored in our case.
On the other hand, the AVG function might be new to you. It's a classic SQL function utilized for calculating the arithmetic mean of a set of values. Simply put, AVG can help us determine an average value, such as the average trophies won per season in Lionel Messi's career.
Example 1: Utilizing The SUM Function
In the above example, we're using the SUM function to find the total trophies won per season in Lionel Messi's career. This is achieved by joining the Seasons and Matches tables on season_id, where Matches records the details of matches played in each season. The GROUP BY clause ensures we get a total trophies count for each season, providing a comprehensive view of Messi's career achievements.
Example 2: Leveraging The AVG Function
Here, we're introducing the AVG function to find the average trophies won per season in Lionel Messi's career after 2010. By filtering matches based on the date condition (YEAR(Matches.date) > 2010), we focus on more recent seasons. The AVG function calculates the arithmetic mean of trophies won across these seasons, offering insights into Messi's consistent performance over time.
