Aggregate Functions as Window Functions: Concept
Module: Window Functions
Think of aggregate window functions as having superpowers compared to regular GROUP BY. GROUP BY is like taking a group photo - everyone gets squished into one summary picture. Window functions are like having a personal photographer follow each person around, taking individual shots while also knowing what the whole group looks like. You get to keep every individual row (the detail) while also seeing the big picture (the aggregate). It's the best of both worlds - detailed data AND summary statistics in the same result set.
**
**The Fundamental Difference:**
**GROUP BY Aggregates:**
- Collapse rows into summary groups
- Lose individual row details
- One result row per group
- Cannot mix detail and aggregate columns
**Window Function Aggregates:**
- Keep all individual rows
- Add aggregate calculations as new columns
- Same number of rows as input
- Mix detail and aggregate data freely
```sql
-- GROUP BY: Collapses to summary
SELECT department, SUM(salary) as total_salary
FROM employees
GROUP BY department;
-- Result: 3 rows (one per department)
-- Window Function: Preserves all rows
SELECT employee_name, department, salary,
SUM(salary) OVER(PARTITION BY department) as dept_total_salary
FROM employees;
-- Result: 50 rows (all employees) with department totals added
```
**Core Aggregate Functions as Window Functions:**
**1. SUM() - The Running Total Master:**
```sql
-- Running total (cumulative sum)
SELECT
order_date,
daily_sales,
SUM(daily_sales) OVER(ORDER BY order_date) as running_total
FROM daily_sales;
-- Percentage of total
SELECT
product_name,
sales_amount,
SUM(sales_amount) OVER() as total_sales,
ROUND(sales_amount * 100.0 / SUM(sales_amount) OVER(), 2) as percentage_of_total