Top Three Dispensed Drugs per State With Ties Using DENSE_RANK
Last updated: November 29, 2026
Quick Overview
From dispenses (store_id, drug_name, quantity, dispensed_at) and stores (store_id, state), return the top three drugs by total quantity dispensed in each state for 2026, keeping ties.
CVS Health
November 29, 20260
0
0 solved
From dispenses (store_id, drug_name, quantity, dispensed_at) and stores (store_id, state), return the top three drugs by total quantity dispensed in each state for 2026, keeping ties.
CVS runs roughly nine thousand retail pharmacies, and supply chain and merchandising analysts often need state-level rankings. It is a warm-up that checks grouping before ranking and knowing which ranking function fits the tie requirement.
What the Interviewer Expects
- Aggregates quantity by state and drug before ranking
- Chooses DENSE_RANK to keep ties
- Filters to the correct date range with a half-open interval
- Filters on rank in an outer query, not WHERE on the window
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- What would change if you used ROW_NUMBER or RANK?
- How would you show each drug's share of the state's total?
- How would you compare 2026 ranks against 2025 ranks?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
dispenses(store_id, drug_name, quantity, dispensed_at) and stores(store_id, state). Quantity is in units dispensed. "Ties kept" means if two drugs share third place, both appear....
Approach
Join to get state, sum quantity per state and drug for 2026, apply DENSE_RANK() partitioned by state ordered by total descending, then keep rank 3 or better in an outer query, because window functio...