Loading workspace environment...
Master analytical SQL queries using WITH (CTEs), ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running cumulative sums.
WITH ranked_data AS (SELECT ... FROM ...) SELECT * FROM ranked_data;Common Table Expression for modular queries.ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)Window function computing ranking within partition.CREATE TABLE sales_reps (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
region TEXT NOT NULL,
revenue INTEGER NOT NULL
);
INSERT INTO sales_reps VALUES (1, 'Sarah', 'North', 85000);
INSERT INTO sales_reps VALUES (2, 'Michael', 'North', 92000);
INSERT INTO sales_reps VALUES (3, 'Elena', 'North', 78000);
INSERT INTO sales_reps VALUES (4, 'David', 'South', 95000);
INSERT INTO sales_reps VALUES (5, 'Jessica', 'South', 89000);
-- Rank reps within their region and compute regional cumulative running total
WITH regional_ranks AS (
SELECT
name,
region,
revenue,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS rank_in_region,
SUM(revenue) OVER (PARTITION BY region ORDER BY revenue DESC) AS running_region_total
FROM sales_reps
)
SELECT name, region, revenue, rank_in_region, running_region_total
FROM regional_ranks
WHERE rank_in_region <= 2
ORDER BY region, rank_in_region;name | region | revenue | rank_in_region | running_region_total
--------+--------+---------+----------------+---------------------
Michael | North | 92000 | 1 | 92000
Sarah | North | 85000 | 2 | 177000
David | South | 95000 | 1 | 95000
Jessica | South | 89000 | 2 | 184000SELECT name, ROW_NUMBER() OVER (...) as rank FROM sales WHERE rank <= 2; -- Error!WITH ranked AS (SELECT name, ROW_NUMBER() OVER (...) as rank FROM sales) SELECT * FROM ranked WHERE rank <= 2;Architectural Explanation: Window functions cannot be filtered directly in the `WHERE` clause because WHERE executes before window evaluation. Wrap in a CTE first.
Given monthly sales data, write a query using `LAG()` to calculate the difference between the current month revenue and the previous month revenue.