Using UNION ALL, find clients that appear in multiple states and compute the difference in total revenue between those states. Then use LEFT JOIN, GROUP BY, and ORDER BY DESC to display the results.
💡 Model Answer
First, identify clients that exist 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 ). Next, calculate revenue per client‑state pair and use UNION ALL to combine the two sides of the comparison: , revenue_by_state AS ( SELECT c.client_id, s.state_name, SUM(r.revenue) AS state_revenue FROM client c JOIN state s ON c.state_id = s.state_id JOIN revenue r ON c.client_id = r.client_id GROUP BY c.client_id, s.state_name ). Now compute the revenue difference for each client by joining the two state rows together. A common trick is to self‑join the revenue_by_state table on client_id and subtract the values: , revenue_diff AS ( SELECT a.client_id, a.state_name AS state_a, b.state_name AS state_b, a.state_revenue - b.state_revenue AS diff FROM revenue_by_state a JOIN revenue_by_state b ON a.client_id = b.client_id AND a.state_name < b.state_name ). Finally, left‑join this diff set back to the client table, group by client, and order by the absolute difference descending: SELECT c.client_id, SUM(ABS(rd.diff)) AS total_diff FROM client c LEFT JOIN revenue_diff rd ON c.client_id = rd.client_id GROUP BY c.client_id ORDER BY total_diff DESC;. This approach uses UNION ALL indirectly through the revenue_by_state CTE, calculates pairwise differences, and aggregates the results. It demonstrates handling of multi‑dimensional joins, set operations, and aggregation.
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