InterviewStack.io LogoInterviewStack.io

Advanced SQL: Window Functions & CTEs for Complex Analysis Questions

Advanced SQL techniques using window functions (ROW_NUMBER, RANK, DENSE_RANK, etc.) and common table expressions (CTEs), including recursive queries, for complex data analysis, ranking and analytics patterns, cumulative totals, and multi-step data transformations within relational databases and data warehousing contexts.

HardTechnical
55 practiced
Design SQL to unpivot/wide-to-long transform event counters (many columns representing event types) into a tall feature table for modeling. Assume `daily_events(user_id, dt, event_type_A_count, event_type_B_count, ..., event_type_N_count)`. Provide patterns for Postgres and BigQuery and discuss strategies when event types are high-cardinality or dynamic.
HardTechnical
56 practiced
Provide a SQL derivation and a working implementation that computes an exponentially time-decayed sum per user without using a recursive CTE by transforming the recurrence into a closed form. Input: `events(user_id, date, amount)` where decay is per day. Explain numerical pitfalls and how you would implement efficiently on large datasets.
MediumTechnical
56 practiced
Using recursion, write SQL to compute for each user the total purchase amount contributed by their referral tree up to depth 3. Tables: `referrals(referrer_id INT, referred_id INT)` and `purchases(user_id INT, amount NUMERIC)`. Output `root_user_id, depth, referred_user_id, referred_amount`, and then aggregate to `root_user_id, total_referred_amount_up_to_depth_3` for use as a feature.
HardTechnical
51 practiced
Extend the referrals aggregation: compute for each user a weighted referrals revenue where each hop's contribution decays by 0.5 per depth up to depth 5. Use a recursive CTE to traverse referrals and prevent cycles. Tables: `referrals(referrer_id, referred_id)` and `purchases(user_id, amount)`. Provide the SQL and discuss how to limit memory blow-up and alternatives.
MediumTechnical
31 practiced
Finance wants a month-to-date revenue trend by product from a daily sales fact table, but some product-day combinations are missing because there were no sales. The report still needs to show zero-revenue days and reset correctly at each month boundary. How would you structure the query and what reference data, if any, would you need?

Unlock Full Question Bank

Get access to hundreds of Advanced SQL: Window Functions & CTEs for Complex Analysis interview questions and detailed answers.

Sign in to Continue

Join thousands of developers preparing for their dream job.