Introduction
To find the top N items in each group from a table, like the best scores per class or highest sales per region.
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY group_column ORDER BY order_column DESC) AS rn FROM table_name ) sub WHERE rn <= N;
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn FROM products ) sub WHERE rn <= 3;
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees ) sub WHERE rn <= 1;
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn FROM orders ) sub WHERE rn <= 2;
CREATE TABLE sales ( region VARCHAR(20), product VARCHAR(20), amount INT ); INSERT INTO sales VALUES ('North', 'Apples', 100), ('North', 'Oranges', 150), ('North', 'Bananas', 120), ('South', 'Apples', 200), ('South', 'Oranges', 180), ('South', 'Bananas', 160); SELECT region, product, amount FROM ( SELECT region, product, amount, ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn FROM sales ) sub WHERE rn <= 2 ORDER BY region, rn;
ROW_NUMBER() OVER (PARTITION BY column ORDER BY column) clause do in a SQL query?employees table?sales with columns region, salesperson, and amount, what will this query return?SELECT region, salesperson, amount FROM (SELECT region, salesperson, amount, ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn FROM sales) AS ranked WHERE rn = 1;
orders table:SELECT customer_id, order_id, order_date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rank FROM orders WHERE rank <= 3;
products table with columns category, product_id, and price. You want to find the top 2 most expensive products per category, but if two products have the same price, include both even if it means more than 2 per category. Which query achieves this?Pass the test and this pattern moves unknown