WINDOW clause
Applies to: Databricks SQL Databricks Runtime
The window clause allows you to define and name one or more distinct window specifications once and share them across many window functions within the same query.
Syntax
WINDOW { window_name AS window_spec } [, ...]
Parameters
window_name
An identifier by which the window specification can be referenced. The identifier must be unique within the WINDOW clause.
window_spec
A window specification to be shared across one or more window functions.
Examples
> CREATE TABLE employees
(name STRING, dept STRING, salary INT, age INT);
> INSERT INTO employees
VALUES ('Lisa', 'Sales', 10000, 35),
('Evan', 'Sales', 32000, 38),
('Fred', 'Engineering', 21000, 28),
('Alex', 'Sales', 30000, 33),
('Tom', 'Engineering', 23000, 33),
('Jane', 'Marketing', 29000, 28),
('Jeff', 'Marketing', 35000, 38),
('Paul', 'Engineering', 29000, 23),
('Chloe', 'Engineering', 23000, 25);
> SELECT round(avg(age) OVER win, 1) AS salary,
round(avg(salary) OVER win, 1) AS avgsalary,
min(salary) OVER win AS minsalary,
max(salary) OVER win AS maxsalary,
count(1) OVER win AS numEmps
FROM employees
WINDOW win AS (ORDER BY age
ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING);
25.3 27000.0 23000 29000 3
26.0 25500.0 21000 29000 4
27.4 25000.0 21000 29000 5
29.4 25200.0 21000 30000 5
31.4 22600.0 10000 30000 5
33.4 23800.0 10000 35000 5
35.4 26000.0 10000 35000 5
36.0 26750.0 10000 35000 4
37.0 25666.7 10000 35000 3