Window functions allow for calculations across a subset of rows related to the current row. Unlike standard aggregation, they do not collapse the result set but instead provide analytical insights like ranking, running totals, and moving averages.
A window function uses over, which defines a partitioning and ordering context for the function.
query:
select:
- customer_id
- total_spent
- rank:
function: rank
over:
partition_by: null
order_by: total_spent DESC
from:
subquery:
select: [customer_id, sum: total_price as total_spent]
from: orders
group_by: customer_idSQLY supports ranking functions such as:
rank- Assigns a unique rank, with gaps for ties.dense_rank- Assigns ranks without gaps.row_number- Assigns a unique sequential row number.
query:
select:
- order_id
- customer_id
- order_date
- row_num:
function: row_number
over:
partition_by: customer_id
order_by: order_date DESC
from: ordersWindow functions can calculate cumulative values over a partitioned set.
query:
select:
- order_id
- customer_id
- order_date
- total_price
- running_total:
function: sum
over:
partition_by: customer_id
order_by: order_date ASC
rows: unbounded preceding
from: ordersquery:
select:
- order_id
- customer_id
- order_date
- total_price
- moving_avg:
function: avg
over:
partition_by: customer_id
order_by: order_date ASC
rows: 2 preceding
from: orders- Window functions operate over a partitioned subset of data.
- Use
rank,dense_rank, androw_numberfor ordering analysis. sumandavgcan compute running totals and moving averages.