{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction\n", "\n", "In the [Intro to SQL micro-course](https://www.kaggle.com/learn/intro-to-sql), you learned how to use [**aggregate functions**](https://www.kaggle.com/dansbecker/group-by-having-count), which perform calculations based on sets of rows. In this tutorial, you'll learn how to define **analytic functions**, which also operate on a set of rows. However, unlike aggregate functions, analytic functions return a (potentially different) value for each row in the original table.\n", "\n", "Analytic functions allow us to perform complex calculations with relatively straightforward syntax. For instance, we can quickly calculate moving averages and running totals, among other quantities.\n", "\n", "# Syntax\n", "\n", "To understand how to write analytic functions, we'll work with a small table containing data from two different people who are training for a race. The `id` column identifies each runner, the `date` column holds the day of the training session, and `time` shows the time (in minutes) that the runner dedicated to training. Say we'd like to calculate a moving average of the training times for each runner, where we always take the average of the current and previous training sessions. We can do this with the following query:\n", "\n", "![first_query](https://storage.googleapis.com/kaggle-media/learn/images/rehp8HM.png)\n", "\n", "All analytic functions have an **OVER** clause, which defines the sets of rows used in each calculation. The **OVER** clause has three (optional) parts:\n", "- The **PARTITION BY** clause divides the rows of the table into different groups. In the query above, we divide by `id` so that the calculations are separated by runner.\n", "- The **ORDER BY** clause defines an ordering within each partition. In the sample query, ordering by the `date` column ensures that earlier training sessions appear first.\n", "- The final clause (`ROWS BETWEEN 1 PRECEDING AND CURRENT ROW`) is known as a **window frame** clause. It identifies the set of rows used in each calculation. We can refer to this group of rows as a **window**. (_Actually, analytic functions are sometimes referred to as **analytic window functions** or simply **window functions**!_) \n", "\n", "![first_query](https://storage.googleapis.com/kaggle-media/learn/images/GjiKlA7.png)\n", "\n", "# (More on) window frame clauses\n", "\n", "There are many ways to write window frame clauses:\n", "- `ROWS BETWEEN 1 PRECEDING AND CURRENT ROW` - the previous row and the current row.\n", "- `ROWS BETWEEN 3 PRECEDING AND 1 FOLLOWING` - the 3 previous rows, the current row, and the following row. \n", "- `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` - all rows in the partition.\n", "\n", "Of course, this is not an exhaustive list, and you can imagine that there are many more options! In the code below, you'll see some of these clauses in action.\n", "\n", "# Three types of analytic functions\n", "\n", "The example above uses only one of many analytic functions. BigQuery supports a wide variety of analytic functions, and we'll explore a few here. For a complete listing, you can take a look at the [documentation](https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts).\n", "\n", "### 1) Analytic aggregate functions\n", "\n", "As you might recall, **AVG()** (from the example above) is an aggregate function. The **OVER** clause is what ensures that it's treated as an analytic (aggregate) function. **Aggregate functions** take all of the values within the window as input and return a single value.\n", "\n", "- **MIN()** (or **MAX()**) - Returns the minimum (or maximum) of input values\n", "- **AVG()** (or **SUM()**) - Returns the average (or sum) of input values \n", "- **COUNT()** - Returns the number of rows in the input\n", "\n", "### 2) Analytic navigation functions\n", "\n", "**Navigation functions** assign a value based on the value in a (usually) different row than the current row.\n", "- **FIRST_VALUE()** (or **LAST_VALUE()**) - Returns the first (or last) value in the input\n", "- **LEAD()** (and **LAG()**) - Returns the value on a subsequent (or preceding) row\n", "\n", "### 3) Analytic numbering functions\n", "\n", "**Numbering functions** assign integer values to each row based on the ordering.\n", "- **ROW_NUMBER()** - Returns the order in which rows appear in the input (starting with `1`)\n", "- **RANK()** - All rows with the same value in the ordering column receive the same rank value, where the next row receives a rank value which increments by the number of rows with the previous rank value.\n", "\n", "\n", "\n", "# Example\n", "\n", "We'll work with the [San Francisco Open Data](https://www.kaggle.com/datasf/san-francisco) dataset. We begin by reviewing the first several rows of the `bikeshare_trips` table. (_The corresponding code is hidden, but you can un-hide it by clicking on the \"Code\" button below._)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_kg_hide-input": true }, "outputs": [], "source": [ "#$HIDE_INPUT$\n", "from google.cloud import bigquery\n", "\n", "# Create a \"Client\" object\n", "client = bigquery.Client()\n", "\n", "# Construct a reference to the \"san_francisco\" dataset\n", "dataset_ref = client.dataset(\"san_francisco\", project=\"bigquery-public-data\")\n", "\n", "# API request - fetch the dataset\n", "dataset = client.get_dataset(dataset_ref)\n", "\n", "# Construct a reference to the \"bikeshare_trips\" table\n", "table_ref = dataset_ref.table(\"bikeshare_trips\")\n", "\n", "# API request - fetch the table\n", "table = client.get_table(table_ref)\n", "\n", "# Preview the first five lines of the table\n", "client.list_rows(table, max_results=5).to_dataframe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each row of the table corresponds to a different bike trip, and we can use an analytic function to calculate the cumulative number of trips for each date in 2015." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Query to count the (cumulative) number of trips per day\n", "num_trips_query = \"\"\"\n", " WITH trips_by_day AS\n", " (\n", " SELECT DATE(start_date) AS trip_date,\n", " COUNT(*) as num_trips\n", " FROM `bigquery-public-data.san_francisco.bikeshare_trips`\n", " WHERE EXTRACT(YEAR FROM start_date) = 2015\n", " GROUP BY trip_date\n", " )\n", " SELECT *,\n", " SUM(num_trips) \n", " OVER (\n", " ORDER BY trip_date\n", " ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n", " ) AS cumulative_trips\n", " FROM trips_by_day\n", " \"\"\"\n", "\n", "# Run the query, and return a pandas DataFrame\n", "num_trips_result = client.query(num_trips_query).result().to_dataframe()\n", "num_trips_result.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The query uses a [common table expression (CTE)](https://www.kaggle.com/dansbecker/as-with) to first calculate the daily number of trips. Then, we use **SUM()** as an aggregate function.\n", "- Since there is no **PARTITION BY** clause, the entire table is treated as a single partition.\n", "- The **ORDER BY** clause orders the rows by date, where earlier dates appear first. \n", "- By setting the **window frame** clause to `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`, we ensure that all rows up to and including the current date are used to calculate the (cumulative) sum. (_**Note**: If you read [the documentation](https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts), you'll see that this is the default behavior, and so the query would return the same result if we left out this **window frame** clause._)\n", "\n", "The next query tracks the stations where each bike began (in `start_station_id`) and ended (in `end_station_id`) the day on October 25, 2015." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Query to track beginning and ending stations on October 25, 2015, for each bike\n", "start_end_query = \"\"\"\n", " SELECT bike_number,\n", " TIME(start_date) AS trip_time,\n", " FIRST_VALUE(start_station_id)\n", " OVER (\n", " PARTITION BY bike_number\n", " ORDER BY start_date\n", " ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING\n", " ) AS first_station_id,\n", " LAST_VALUE(end_station_id)\n", " OVER (\n", " PARTITION BY bike_number\n", " ORDER BY start_date\n", " ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING\n", " ) AS last_station_id,\n", " start_station_id,\n", " end_station_id\n", " FROM `bigquery-public-data.san_francisco.bikeshare_trips`\n", " WHERE DATE(start_date) = '2015-10-25' \n", " \"\"\"\n", "\n", "# Run the query, and return a pandas DataFrame\n", "start_end_result = client.query(start_end_query).result().to_dataframe()\n", "start_end_result.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The query uses both **FIRST_VALUE()** and **LAST_VALUE()** as analytic functions.\n", "- The **PARTITION BY** clause breaks the data into partitions based on the `bike_number` column. Since this column holds unique identifiers for the bikes, this ensures the calculations are performed separately for each bike.\n", "- The **ORDER BY** clause puts the rows within each partition in chronological order.\n", "- Since the **window frame** clause is `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`, for each row, its entire partition is used to perform the calculation. (_This ensures the calculated values for rows in the same partition are identical._)\n", " \n", "# Your turn\n", "\n", "**[Write your own](#$NEXT_NOTEBOOK_URL$)** analytic functions!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 1 }