Home › Interview Questions › Write a SQL query that uses a CTE to find clients …

Write a SQL query that uses a CTE to find clients that operate in multiple states, calculates the difference between the maximum and minimum revenue per client, then joins the revenue and client tables, groups by client, orders by revenue difference descending, and limits the result to the top record.

🔴 Hard Coding Mid level
2Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

The CTE first isolates clients that have entries in more than one state: WITH multi_state_clients AS ( SELECT client_id FROM client GROUP BY client_id HAVING COUNT(DISTINCT state_id) > 1 ), revenue_by_client AS ( SELECT c.client_id, SUM(r.revenue) AS total_rev FROM client c JOIN revenue r ON c.client_id = r.client_id GROUP BY c.client_id ). Next, compute the max and min revenue for each client across all states. If revenue is stored per state, you would join the state table and aggregate per client‑state, then compute the difference: , rev_stats AS ( SELECT c.client_id, MAX(r.revenue) AS max_rev, MIN(r.revenue) AS min_rev, MAX(r.revenue) - MIN(r.revenue) AS rev_diff FROM client c JOIN revenue r ON c.client_id = r.client_id WHERE c.client_id IN (SELECT client_id FROM multi_state_clients) GROUP BY c.client_id ). Finally, join back to the client table to bring in business data, group by client, order by the revenue difference descending, and limit to one row: SELECT c.client_id, c.client_name, rs.rev_diff FROM client c JOIN rev_stats rs ON c.client_id = rs.client_id ORDER BY rs.rev_diff DESC LIMIT 1;. This query demonstrates the use of CTEs for readability, conditional aggregation, and the ability to surface the client with the largest revenue swing across states. It is a common pattern in analytical reporting where you need to surface outliers.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500