Introduction
Window functions and GROUP BY help summarize data, but window functions keep all rows while GROUP BY groups rows into one result each.
SELECT column1, aggregate_function(column2) OVER (PARTITION BY column3 ORDER BY column4) AS window_result FROM table; -- vs -- SELECT column1, aggregate_function(column2) AS group_result FROM table GROUP BY column1;
SELECT employee, department, SUM(sales) OVER (PARTITION BY department) AS dept_sales FROM sales_data;
SELECT department, SUM(sales) AS dept_sales FROM sales_data GROUP BY department;
SELECT employee, sales, RANK() OVER (ORDER BY sales DESC) AS sales_rank FROM sales_data;
CREATE TABLE sales_data ( employee VARCHAR(20), department VARCHAR(20), sales INT ); INSERT INTO sales_data VALUES ('Alice', 'Electronics', 100), ('Bob', 'Electronics', 150), ('Carol', 'Clothing', 200), ('Dave', 'Clothing', 50); -- Window function example SELECT employee, department, sales, SUM(sales) OVER (PARTITION BY department) AS dept_total_sales FROM sales_data ORDER BY department, employee; -- GROUP BY example SELECT department, SUM(sales) AS dept_total_sales FROM sales_data GROUP BY department ORDER BY department;
GROUP BY clause and a window function in SQL?GROUP BY behaviorGROUP BY groups rows by specified columns and returns one row per group with aggregated results.GROUP BY groups rows and returns one row per group; window functions keep all rows and add summary data. -> Option CGROUP BY groups rows [OK]SUM() OVER (PARTITION BY ... ORDER BY ...), which is the correct syntax for running totals per employee.sales(employee_id, sale_amount) with data:1, 100
1, 200
2, 150
2, 50SELECT employee_id, sale_amount, SUM(sale_amount) OVER (PARTITION BY employee_id) AS total_sales FROM sales ORDER BY employee_id, sale_amount;
SELECT employee_id, sale_amount, SUM(sale_amount) OVER (PARTITION BY employee_id ORDER BY sale_date) AS running_total FROM sales GROUP BY employee_id, sale_amount, sale_date;
AVG() OVER (PARTITION BY department_id) adds average without grouping rows.Pass the test and this pattern moves unknown