Days Between Consecutive Refills Using LAG for Each Member
Last updated: November 29, 2026
Quick Overview
From a prescription_fills table, return each fill with the number of days since the same member's previous fill of the same drug, and the days of supply that should have remained. Flag fills that arrive more than 7 days late.
CVS Health
November 29, 20260
0
0 solved
From a prescription_fills table, return each fill with the number of days since the same member's previous fill of the same drug, and the days of supply that should have remained. Flag fills that arrive more than 7 days late.
A common first SQL screen for CVS Pharmacy analytics roles, framed around refill timing that drives ReadyFill and refill reminder programs. The interviewer checks basic window function fluency: PARTITION BY, ORDER BY and LAG with sensible NULL handling.
What the Interviewer Expects
- Partitions by member and drug, orders by fill date
- Uses LAG for prior fill date and prior days supply
- Computes gap minus prior supply to get lateness
- Handles the first fill (NULL lag) explicitly
- Explains tie handling on same-day fills
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
- How would you get the average lateness per store?
- What changes if you need the gap to the next fill instead?
- How would you ignore fills that were reversed within 14 days?
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
prescription_fills(fill_id, member_id, ndc, fill_date DATE, days_supply INT, store_id). I will treat the drug at the NDC level here, and mention that grouping by a generic product identifier is usua...
Approach
Use LAG partitioned by member and drug to fetch the previous fill date and its days supply. Days late = (current fill date minus previous fill date) minus previous days supply. Positive means the me...