SQL Query to Calculate Days Between First and Last Post in 2021

🚀 Another SQL problem solved — and this one was a great exercise in aggregation + date handling! **Problem:** For each user, find the number of days between their first and last post in 2021 — but only include users who posted at least twice. **My Approach:** * Filter data for the year 2021 * Group by `user_id` * Use `MIN()` and `MAX()` to get first & last post dates * Subtract dates to get the duration * Use `HAVING` to ensure at least 2 posts **Final Query (PostgreSQL):** SELECT    user_id,   MAX(post_date)::date - MIN(post_date)::date AS days_between FROM posts WHERE EXTRACT(YEAR FROM post_date) = 2021 GROUP BY user_id HAVING COUNT(*) >= 2; **Key Learnings 💡** * `MAX(date) - MIN(date)` is a clean way to compute activity span * `HAVING` is essential when filtering aggregated results * Type casting (`::date`) ensures correct subtraction behavior * Always think: filter → group → aggregate → filter again Shoutout to Nick Singh 📕🐒 for creating and sharing such practical SQL problems 🙌 #SQL #PostgreSQL #DataAnalytics #BackendDevelopment #DataEngineering  #InterviewPrep

To view or add a comment, sign in

Explore content categories