SUM() OVER() is a window function often used to calculate a running total without grouping rows.
Sample Employees Table
| EmployeeID | EmployeeName | Salary |
|---|---|---|
| 1 | Alice | 3000 |
| 2 | Bob | 4000 |
| 3 | Charlie | 2500 |
| 4 | David | 5000 |
| 5 | Emma | 3500 |
Running Total of Salaries
SELECT
EmployeeID,
EmployeeName,
Salary,
SUM(Salary) OVER (
ORDER BY EmployeeID
) AS RunningTotal
FROM Employees;
Output
| EmployeeID | EmployeeName | Salary | RunningTotal |
|---|---|---|---|
| 1 | Alice | 3000 | 3000 |
| 2 | Bob | 4000 | 7000 |
| 3 | Charlie | 2500 | 9500 |
| 4 | David | 5000 | 14500 |
| 5 | Emma | 3500 | 18000 |
How it works
For each row:
Alice → 3000
Alice + Bob → 7000
Alice + Bob + Charlie → 9500
Alice + Bob + Charlie + David → 14500
Alice + Bob + Charlie + David + Emma → 18000
The window function is effectively doing:
SUM(Salary) OVER (
ORDER BY EmployeeID
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
which means:
Start from the first row (
UNBOUNDED PRECEDING)Keep adding values up to the current row (
CURRENT ROW)
Running Total by Department
Suppose the table has a department column:
| EmployeeID | EmployeeName | Department | Salary |
|---|---|---|---|
| 1 | Alice | HR | 3000 |
| 2 | Bob | HR | 4000 |
| 3 | Charlie | IT | 2500 |
| 4 | David | IT | 5000 |
| 5 | Emma | HR | 3500 |
SELECT
EmployeeID,
EmployeeName,
Department,
Salary,
SUM(Salary) OVER (
PARTITION BY Department
ORDER BY EmployeeID
) AS DeptRunningTotal
FROM Employees;
Output
| EmployeeID | EmployeeName | Department | Salary | DeptRunningTotal |
|---|---|---|---|---|
| 1 | Alice | HR | 3000 | 3000 |
| 2 | Bob | HR | 4000 | 7000 |
| 5 | Emma | HR | 3500 | 10500 |
| 3 | Charlie | IT | 2500 | 2500 |
| 4 | David | IT | 5000 | 7500 |
Here, PARTITION BY Department restarts the running total for each department.
Formula:
SUM(column_name) OVER (
[PARTITION BY partition_column]
ORDER BY order_column
)
This is one of the most common SQL interview questions involving window functions.
No comments:
Post a Comment