View a markdown version of this page

WINDOW clause - Amazon Athena

WINDOW clause

The WINDOW clause defines named windows. A window function refers to one with OVER window_name. It can also start from a named window that has no ORDER BY of its own and add one, as in OVER (w ORDER BY amount DESC).

A window definition can have PARTITION BY, which splits the rows into groups that are computed separately, and ORDER BY, which orders the rows in each partition. It can also have a frame, such as ROWS BETWEEN 1 PRECEDING AND CURRENT ROW, which limits the rows that each calculation sees.

Syntax

WINDOW window_name AS ( [ existing_window_name ] [ PARTITION BY expression [, ...] ] [ ORDER BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ] [ frame ] ) [, ...] frame: { ROWS | RANGE | GROUPS } BETWEEN frame_start AND frame_end

Examples

For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.

The following SQL query defines the window w once, uses it for a regional total, and extends it with ORDER BY to rank the orders in each region.

SELECT order_id, region, amount, sum(amount) OVER w AS region_total, rank() OVER ( w ORDER BY amount DESC NULLS LAST ) AS rank_in_region FROM sales_db.sales_parquet WINDOW w AS (PARTITION BY region) ORDER BY region, rank_in_region

The query returns the following results.

order_id region amount region_total rank_in_region

1

east

120.50

162.75

1

3

east

42.25

162.75

2

6

east

NULL

162.75

3

4

north

310.00

310.00

1

2

west

75.00

93.75

1

5

west

18.75

93.75

2

The following SQL query uses a frame to add each order's amount to the amount of the order before it. For the last order, whose amount is NULL, sum skips the NULL value.

SELECT order_id, amount, sum(amount) OVER w AS two_order_total FROM sales_db.sales_parquet WINDOW w AS ( ORDER BY order_id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW ) ORDER BY order_id

The query returns the following results.

order_id amount two_order_total

1

120.50

120.50

2

75.00

195.50

3

42.25

117.25

4

310.00

352.25

5

18.75

328.75

6

NULL

18.75