~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ License); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
:::info
Apache Druid supports two query languages: [Druid SQL](sql.md) and [native queries](querying.md).
This document describes the SQL language.
Window functions are an [experimental](../development/experimental.md) feature.
Development and testing are still at early stage. Feel free to try window functions and provide your feedback.
Windows functions are not currently supported by multi-stage-query engine so you cannot use them in SQL-based ingestion.
Set the context parameter `enableWindowing: true` to use window functions.
:::
Window functions in Apache Druid produce values based upon the relationship of one row within a window of rows to the other rows within the same window. A window is a group of related rows within a result set. For example, rows with the same value for a specific dimension.
Window functions in Druid require a GROUP BY statement. Druid performs the row-level aggregations for the GROUP BY before performing the window function calculations.
The following example organizes results with the same `channel` value into windows. For each window, the query returns the rank of each row in ascending order based upon its `changed` value.
- PARTITION BY indicates the dimension that defines window boundaries
- ORDER BY specifies the order of the rows within the windows
An empty OVER clause or the absence of a PARTITION BY clause indicates that all data belongs to a single window.
In the following example, the following OVER clause example sets the window dimension to `channel` and orders the results by the absolute value of `delta` ascending:
```sql
...
RANK() OVER (PARTITION BY channel ORDER BY ABS(delta) ASC)
...
```
Window frames, set in ROWS and RANGE expressions, limit the set of rows used for the windowed aggregation.
ROWS and RANGE accept the following values for `range start` and `range end`:
- UNBOUNDED PRECEDING: from the beginning of the window as ordered by the order expression
- _N_ ROWS PRECEDING: _N_ rows before the current row as ordered by the order expression
- CURRENT ROW: the current row
- _N_ ROWS FOLLOWING: _N_ rows after the current row as ordered by the order expression
- UNBOUNDED FOLLOWING: to the end of the window as ordered by the order expression
See [Example with window frames](#example-with-window-frames) for more detail.
Druid applies the GROUP BY dimensions before calculating all non-window aggregation functions. Then it applies the window function over the aggregated results.
Sometimes windows are called partitions. However, the partitioning for window functions are a shuffle (partition) of the result set created at query time and is not to be confused with Druid's segment partitioning feature which partitions data at ingest time.
When a window only specifies PARTITION BY partition expression, Druid calculates the aggregate window function over all the rows that share a value within the selected dataset.
The following example demonstrates a query that uses two different windows—`PARTITION BY channel` and `PARTITION BY user`—to calculate the total activity in the channel and total activity by the user so that they can be compared to individual hourly activity:
```sql
SELECT
TIME_FLOOR(__time, 'PT1H') as time_hour,
channel,
user,
SUM(delta) AS hourly_user_changes,
SUM(SUM(delta)) OVER (PARTITION BY user) AS total_user_changes,
SUM(SUM(delta)) OVER (PARTITION BY channel) AS total_channel_changes
FROM "wikipedia"
WHERE channel IN ('#kk.wikipedia', '#lt.wikipedia')
AND __time BETWEEN '2016-06-27' AND '2016-06-28'
GROUP BY TIME_FLOOR(__time, 'PT1H'), 2, 3
ORDER BY channel, TIME_FLOOR(__time, 'PT1H'), user
In this example, the dataset is filtered for a single day. Therefore the window function results represent the total activity for the day, for the `user` and for the `channel` dimensions respectively.
This type of result helps you analyze the impact of an individual user's hourly activity:
- the impact to the channel by comparing `hourly_user_changes` to `total_channel_changes`
- the impact of each user over the channel by `total_user_changes` to `total_channel_changes`
- the progress of each user's individual activity by comparing `hourly_user_changes` to `total_user_changes`
#### Window frame guardrails
Druid has guardrail logic to prevent you from executing window function queries with window frame expressions that might return unexpected results.
For example:
- You cannot set expressions as bounds for window frames.
- You can only use a RANGE frames when both endpoints are unbounded or current row.
| `ROW_NUMBER()` | Returns the number of the row within the window starting from 1 |
| `RANK()` | Returns the rank with gaps for a row within a window. For example, if two rows tie for rank 1, the next rank is 3 |
| `DENSE_RANK()` | Returns the rank for a row within a window without gaps. For example, if two rows tie for rank of 1, the subsequent row is ranked 2. |
| `PERCENT_RANK()` | Returns the relative rank of the row calculated as a percentage according to the formula: `RANK() OVER (window) / COUNT(1) OVER (window)` |
| `CUME_DIST()` | Returns the cumulative distribution of the current row within the window calculated as number of window rows at the same rank or higher than current row divided by total window rows. The return value ranges between `1/number of rows` and 1 |
| `NTILE(tiles)` | Divides the rows within a window as evenly as possible into the number of tiles, also called buckets, and returns the value of the tile that the row falls into | None |
| `LAG(expr[, offset])` | If you do not supply an `offset`, returns the value evaluated at the row preceding the current row. Specify an offset number, `n`, to return the value evaluated at `n` rows preceding the current one |
| `LEAD(expr[, offset])` | If you do not supply an `offset`, returns the value evaluated at the row following the current row. Specify an offset number `n` to return the value evaluated at `n` rows following the current one; if there is no such row, returns the given default value |
| `FIRST_VALUE(expr)` | Returns the value evaluated for the expression for the first row within the window |
| `LAST_VALUE(expr)` | Returns the value evaluated for the expression for the last row within the window |
The following example illustrates all of the built-in window functions to compare the number of characters changed per event for a channel in the Wikipedia data set.
```sql
SELECT FLOOR(__time TO DAY) AS event_time,
channel,
ABS(delta) AS change,
ROW_NUMBER() OVER w AS row_no,
RANK() OVER w AS rank_no,
DENSE_RANK() OVER w AS dense_rank_no,
PERCENT_RANK() OVER w AS pct_rank,
CUME_DIST() OVER w AS cumulative_dist,
NTILE(4) OVER w AS ntile_val,
LAG(ABS(delta), 1, 0) OVER w AS lag_val,
LEAD(ABS(delta), 1, 0) OVER w AS lead_val,
FIRST_VALUE(ABS(delta)) OVER w AS first_val,
LAST_VALUE(ABS(delta)) OVER w AS last_val
FROM wikipedia
WHERE channel IN ('#kk.wikipedia', '#lt.wikipedia')
GROUP BY channel, ABS(delta), FLOOR(__time TO DAY)
WINDOW w AS (PARTITION BY channel ORDER BY ABS(delta) ASC)
The example defines multiple window specifications in the WINDOW clause that you can use for various window function calculations.
The query uses two windows:
-`cumulative` is partitioned by channel and includes all rows from the beginning of partition up to the current row as ordered by `__time` to enable cumulative aggregation
-`moving5` is also partitioned by channel but only includes up to the last four rows and the current row as ordered by time
The number of rows considered for the `moving5` window for the `count5` column:
- starts at a single row because there are no rows before the current one
- grows up to five rows as defined by `ROWS BETWEEN 4 ROWS PRECEDING AND CURRENT ROW`