Find Top N Salary Earners by City and Department
Given a table containing employee details with columns for employee, salary, city, and department, which SQL window function would you typically use to assign a unique row number within each city and department ordered by salary descending? For example, generating row numbers to pick the top three salary earners in each group.
- ROW_NUMBER() OVER (PARTITION BY city, department ORDER BY salary DESC)
- COUNT(*) GROUP BY city, department
- MAX(salary) OVER (ORDER BY city, department)
- SUM(salary) PARTITION BY department
- ROW_COUNT() IN city, department
Moving Average Calculation
If you need to calculate a moving average of the last 5 order amounts in a sales table, which window function would be most appropriate to use in combination with the AVG() function?
- ROWS BETWEEN 4 PRECEDING AND CURRENT ROW
- GROUP BY 5 ROWS
- DISTINCT ON LAST 5 ROWS
- LIMIT 5 PER ORDER
- ORDER BY DESC, TOP 5
Percentile Calculation in SQL
Suppose you want to calculate the 25th and 75th percentile of a column named 'score' in your table. Which SQL function would be the best choice to use for this purpose?
- PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY score)
- RANK() OVER (ORDER BY score ASC)
- AVG(score) GROUP BY 0.25
- DENSERANK(score, 0.25)
- ORDER BY score LIMIT 25 PERCENT
Difference Between RANK() and DENSE_RANK()
In SQL window functions, what is the main difference between RANK() and DENSE_RANK() when used in a query?
- RANK() leaves gaps in ranking for ties, while DENSE_RANK() does not
- DENSE_RANK() assigns the highest value to the lowest item
- RANK() sorts alphabetically; DENSE_RANK() sorts numerically
- DENSE_RANK() requires an extra ORDER BY clause
- RANK() can only be used with GROUP BY
Calculating Incremental Values from Cumulative Data
Given a table with a 'cumulative_sales' column ordered by date, what window function should you use to calculate daily incremental sales (i.e., today's value minus yesterday's), for example, to track daily growth?
- LAG(cumulative_sales, 1) OVER (ORDER BY date)
- RANK() OVER (ORDER BY cumulative_sales)
- MIN(cumulative_sales) GROUP BY date
- SUM(cumulative_sales) PARTITION BY date
- LEAD_SUM(cumulative_sales, 1) GROUP BY date