Window Functions, CTEs, and Range Joins
Thu Apr 09 2026 15:45:26 GMT+0000 (Coordinated Universal Time)
Saved by @yasvanthM
1. The "Top-N" Product Performance (Window Functions) Scenario: You have a SALES table (sale_id, category_id, product_name, revenue). Task: Identify the top 2 highest-grossing products in each category. If there is a tie in revenue, use the product name (alphabetical) as the tie-breaker. Senior Tip: Using ROW_NUMBER() ensures exactly 2 rows per category; RANK() might return more if there are identical revenues. --- 2. Active User "Churn" Detection (Self-Joins & Dates) Scenario: A USER_LOGINS table (user_id, login_date). Task: Find "Retained Users"—defined as users who logged in on two consecutive days. Output the list of unique user_ids. Senior Tip: For IBM DB2 (often used internally), the syntax might be b.login_date - 1 DAY. This tests your ability to handle non-equi joins. --- 3. Handling Missing Data (COALESCE & Aggregations) Scenario: Two tables: EMPLOYEES (emp_id, name) and BONUSES (emp_id, bonus_amount). Not every employee received a bonus. Task: List all employees and their bonus amounts. If an employee received no bonus, display 0. Sort by bonus amount descending. Senior Tip: This tests the Left Join vs. Inner Join distinction. An Inner Join would incorrectly delete employees who didn't get a bonus. ---- The Scenario Table FAMILIES: ID, NAME, FAMILY_SIZE Table COUNTRIES: ID, NAME, MIN_SIZE, MAX_SIZE The Goal: Find the maximum number of tours a single family is eligible for. A family is eligible if their FAMILY_SIZE falls between a country's MIN_SIZE and MAX_SIZE (inclusive). The Solution To solve this, you first calculate the count of eligible countries for every family, and then take the MAX of those counts.



Comments