Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Window Functions | Triggers, Window Functions and DCL
SQL Optimization and Query Features

Window Functions

Svep för att visa menyn

Window functions are powerful SQL tools that allow you to perform calculations across sets of table rows that are related to the current row. Unlike standard aggregate functions, which collapse query results into a single value per group, window functions keep each row of the query result visible while providing additional analytical insights.

A common use for window functions is calculating running totals. Imagine you have a sales table, which tracks each sale made by employees. If you want to see the cumulative sales amount for each employee as you move through their sales chronologically, a window function makes this straightforward.

12345678910111213
SELECT employee_id, sale_date, amount, SUM(amount) OVER ( PARTITION BY employee_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total FROM sales ORDER BY employee_id, sale_date;

In this query, you calculate a running total of sales for each employee. The SUM(amount) function is used as a window function by combining it with the OVER() clause.

The PARTITION BY employee_id part tells SQL to restart the running total for each employee, so each employee's sales are tallied separately. The ORDER BY sale_date inside the OVER() clause ensures that the running total is calculated in chronological order of sales. The ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW specifies that the sum should include all sales from the start up to the current row.

The result is a list showing each sale, the employee who made it, and the cumulative sales amount for that employee up to that point in time. Window functions like this are essential for advanced reporting and analytics, as they let you compare each row to other rows in a flexible, dynamic way without losing detail in your results.

1. What does the OVER() clause do in a window function?

2. How are window functions different from aggregate functions?

3. Can window functions be used with ORDER BY?

question mark

What does the OVER() clause do in a window function?

Vänligen välj det korrekta svaret

question mark

How are window functions different from aggregate functions?

Vänligen välj det korrekta svaret

question mark

Can window functions be used with ORDER BY?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 2
some-alt