Middle
What is the difference between a window function and an aggregate function in SQL?
sobes.tech AI
Answer from AI
An aggregate function in SQL (for example, SUM, AVG, COUNT) computes a single final value for a group of rows and returns one row per group. For example, SUM(salary) will calculate the total salaries for the entire group.
A window function also works with groups of rows, but returns a result for each row, considering the window context (a set of rows around the current one). For example, SUM(salary) OVER (PARTITION BY department) will return the sum of salaries per department for each row, without reducing the result to a single row.
Example:
SELECT employee_id, department, salary,
SUM(salary) OVER (PARTITION BY department) AS dept_salary_sum
FROM employees;
Here, for each row, the sum of salaries within the department will be shown, rather than one row per department as with an aggregate function with GROUP BY.