# BigQuery Soccer Data Analysis - GSP849

## **Overview**

In this lab, you will learn more fundamentals of sports data science by writing and executing queries to query data stored in BigQuery tables. The emphasis of the lab is to illustrate how the database works and answer some interesting questions related to the following topics in soccer.

* Most total goals scored.
    
* Most attempted passes.
    
* Best penalty success rate.
    

The data used in this lab comes from the following sources:

* Pappalardo et al., (2019) **A public data set of spatio-temporal match events in soccer competitions**, Nature Scientific Data 6:236, [https://www.nature.com/articles/s41597-019-0247-7](https://www.nature.com/articles/s41597-019-0247-7)
    
* Pappalardo et al. (2019) **PlayerRank: Data-driven Performance Evaluation and Player Ranking in Soccer via a Machine Learning Approach**. ACM Transactions on Intelligent Systems and Technologies (TIST) 10, 5, Article 59 (September 2019), 27 pages. DOI: [https://doi.org/10.1145/3343172](https://doi.org/10.1145/3343172)
    

## **Objectives**

In this lab, you will learn how to:

* Query soccer match event data in BigQuery.
    
* Write and execute queries that join information from multiple tables.
    

## **Setup and requirements**

### Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click **Start Lab**, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

* Access to a standard internet browser (Chrome browser recommended).
    

**Note:** Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.

* Time to complete the lab---remember, once you start, you cannot pause a lab.
    

**Note:** If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

### How to start your lab and sign in to the Google Cloud console

1. Click the **Start Lab** button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the **Lab Details** panel with the following:
    
    * The **Open Google Cloud console** button
        
    * Time remaining
        
    * The temporary credentials that you must use for this lab
        
    * Other information, if needed, to step through this lab
        
2. Click **Open Google Cloud console** (or right-click and select **Open Link in Incognito Window** if you are running the Chrome browser).
    
    The lab spins up resources, and then opens another tab that shows the **Sign in** page.
    
    ***Tip:*** Arrange the tabs in separate windows, side-by-side.
    
    **Note:** If you see the **Choose an account** dialog, click **Use Another Account**.
    
3. If necessary, copy the **Username** below and paste it into the **Sign in** dialog.
    
    ```apache
    student-00-a39e984f9cb5@qwiklabs.net
    ```
    
    You can also find the **Username** in the **Lab Details** panel.
    
4. Click **Next**.
    
5. Copy the **Password** below and paste it into the **Welcome** dialog.
    
    ```apache
    ylupPmJv2Byc
    ```
    
    You can also find the **Password** in the **Lab Details** panel.
    
6. Click **Next**.
    
    **Important:** You must use the credentials the lab provides you. Do not use your Google Cloud account credentials.
    
    **Note:** Using your own Google Cloud account for this lab may incur extra charges.
    
7. Click through the subsequent pages:
    
    * Accept the terms and conditions.
        
    * Do not add recovery options or two-factor authentication (because this is a temporary account).
        
    * Do not sign up for free trials.
        

After a few moments, the Google Cloud console opens in this tab.

**Note:** To view a menu with a list of Google Cloud products and services, click the **Navigation menu** at the top-left.

![Navigation menu icon](https://cdn.qwiklabs.com/nUxFb6oRFr435O3t6V7WYJAjeDFcrFb16G9wHWp5BzU%3D align="left")

## **Task 1. Open BigQuery**

The BigQuery console provides an interface to query tables, including [public datasets](https://cloud.google.com/bigquery/public-data) offered by BigQuery.

1. In the Cloud Console, from the **Navigation menu** select **BigQuery**:
    

![The Cloud Console navigation menu, wherein the option BigQuery is selected.](https://cdn.qwiklabs.com/j%2Bk6O6L2HAgjQ0USTiWSFzQbFRPixNZBteMfo6mP5mk%3D align="left")

The **Welcome to BigQuery in the Cloud Console** message box opens. This message box provides a link to the quickstart guide and the release notes.

2. Click **Done**.
    

The BigQuery console opens.

![The BigQuery console, which includes the Editor section and the Explorer pane.](https://cdn.qwiklabs.com/EIlHtgwCSWmZ3nC%2Bf8MtP7Th9ptMn7tVDVtaUr31ZnA%3D align="left")

**Note:** The process for creating the dataset and tables is taught in the [BigQuery Soccer Data Ingestion](https://www.cloudskillsboost.google/catalog_lab/4230) lab. In this lab the focus is on learning how to query the information.

Once the tables are created the display will be similar to this:

![The Explorer pane, wherein the soccer file is highlighted within the list of pinned projects.](https://cdn.qwiklabs.com/ux6I76PtUtyI3sViISF80uu1Ju1MlMkXXjNBY5VCFW8%3D align="left")

In the next section, begin to learn the fundamentals of creating queries in BigQuery.

## **Task 2. Matches with the most goals**

In this section, create a query that joins together multiple tables featuring soccer data. Based on the information available, you can perform some basic analytics such as the most total goals scored in a match by both teams (in a specific league).

1. In the Query editor, click "**+**" (Create SQL query).
    
2. Add the following query to the query **Editor**:
    

```sql
SELECT
 date,
 label,
 (team1.score + team2.score) AS totalGoals
FROM
 `soccer.matches` Matches
LEFT JOIN
 `soccer.competitions` Competitions ON
   Matches.competitionId = Competitions.wyId
WHERE
 status = 'Played' AND
 Competitions.name = 'Spanish first division'
ORDER BY
 totalGoals DESC, date DESC
```

Here is what the query will do:

* joins the **matches** table (which has final scores) with the **competitions** table.
    
* filter down to "Spanish first division" matches only.
    
* order by a calculated field that represents total goals in a match.
    

3. Click **Run**.
    

The results are displayed below the query window.

![The Query results page, wherein several results are listed.](https://cdn.qwiklabs.com/up2Og%2FO4FhdKl9guJPARXEcxbAripKT0VBz%2Fdh4U0oM%3D align="left")

Click Check my progress to verify the objective

Check the query has been run

**Check my progress**

In this section BigQuery was used to illustrate how to define a query that shows soccer information. The query creates a filter that displays specific information about matches from a specific league and enables the information to be categorized by a defined field.

## **Task 3. Players with the most passes**

In this section, create a query that joins together multiple tables featuring soccer data. Based on the information available, you can perform some basic analytics such as total passes by players.

1. In the Query editor, click "**+**" (Create SQL query).
    
2. Add the following query into the query **Editor**:
    

```sql
SELECT
 playerId,
 (Players.firstName || ' ' || Players.lastName) AS playerName,
 COUNT(id) AS numPasses

FROM
 `soccer.events` Events

LEFT JOIN
 `soccer.players` Players ON
   Events.playerId = Players.wyId

WHERE
 eventName = 'Pass'

GROUP BY
 playerId, playerName

ORDER BY
 numPasses DESC

LIMIT 10
```

This query:

* joins the **events** table (which has a record of every pass) with the **players** table to get player names from their IDs
    
* groups by player
    
* counts the number of passes for each one
    
* orders by the players with the most passes
    

3. Click **Run**. The results are displayed below the query window.
    

Click Check my progress to verify the objective

Check the query has been run

**Check my progress**

In this section BigQuery was used to illustrate how to define a query that shows player information. The query creates a join that displays specific information about a **playerId** and enables the information to be categorized by a defined field.

In the next section learn more about the existing dataset and explore how it can be used to determine the penalty kick success rate of players.

## **Task 4. Determine penalty kick success rate**

In this section, create a query that joins together multiple tables featuring soccer data. Based on the information available, you can perform some analytics such as the success rate on penalty kicks by each player.

1. In the Query editor, click "**+**" (Create SQL query).
    
2. Copy and paste the following query into the query **Editor**:
    

```sql
SELECT
 playerId,
 (Players.firstName || ' ' || Players.lastName) AS playerName,
 COUNT(id) AS numPKAtt,
 SUM(IF(101 IN UNNEST(tags.id), 1, 0)) AS numPKGoals,

 SAFE_DIVIDE(
   SUM(IF(101 IN UNNEST(tags.id), 1, 0)),
   COUNT(id)
   ) AS PKSuccessRate

FROM
 `soccer.events` Events

LEFT JOIN
 `soccer.players` Players ON
   Events.playerId = Players.wyId

WHERE
 eventName = 'Free Kick' AND
 subEventName = 'Penalty'

GROUP BY
 playerId, playerName

HAVING
 numPkAtt >= 5

ORDER BY
 PKSuccessRate DESC, numPKAtt DESC
```

The query aggregates the number of penalty kick attempts and successful ones by player and filters to those with at least 5 penalty kick attempts before ordering by success rate.

**Note:** The above query joins the **events** table, in this case filtered to only penalty kicks, with the **players** table to get player names from their IDs.

The tags field in the events table uses BigQuery's array functionality (allowing more than 1 tag to be stored per event), so it must be unnested to determine if the kick was good or not (one can confirm that tag 101 represents a goal using the **tags2name** table).

3. Click **Run**. The results are displayed below the query window.
    

Click Check my progress to verify the objective

Check the query has been run

**Check my progress**

In this section BigQuery was used to illustrate how to define a query that shows player information relating to penalty kicks. The query creates a join that displays specific information about a **playerId** and enables more detailed information to be displayed.

## **Task 5. Pop quiz**

Test your understanding of BigQuery by completing the short quiz on the topics covered in this lab.

**How many different Spanish first division matches achieved the highest number of total goals in our data?**

* 1
    
* 3
    
* 6
    

**Which player attempted the most passes in the data?**

* Granit Hkaka
    
* Kyle Walker
    
* Tony Kroos
    

**How many players attempted at least 5 penalty kicks in this data?**

* 20
    
* 3
    
* 16
    

---

## Solution of Lab

%[https://www.youtube.com/watch?v=iXgfT4PpLBU] 

```apache
curl -LO raw.githubusercontent.com/quiccklabs/Labs_solutions/master/BigQuery%20Soccer%20Data%20Analysis/quicklabgsp849.sh
sudo chmod +x quicklabgsp849.sh
./quicklabgsp849.sh
```
