Explain how to calculate a salesperson's percentage of total company sales and their percentage of their team's sales in a single query using aggregate window functions.
Last updated
Put two window aggregates in one SELECT:
SUM(sales) OVER ()gives the company total andSUM(sales) OVER (PARTITION BY team)gives the team total. Divide each row's sales by each.Window functions (aggregates computed with OVER) keep every salesperson row intact, unlike GROUP BY, so both percentages sit side by side.
Multiply by
100.0or cast to decimal to avoid integer truncation.
- https://datalemur.com/blog/sql-window-functions-interview-questions
- https://medium.com/@krthiak/30-sql-window-functionion-questions-for-interviews-day-47-of-100-days-of-data-engineering-ai-and-638bef1af0f6
- https://www.youtube.com/watch?v=5cMLWs1UP5I
- https://www.youtube.com/watch?v=Lb3vfuew7Gk
- https://www.youtube.com/watch?v=x8wFduXs2kk
- https://medium.com/towards-data-engineering/mastering-sql-recursive-ctes-key-concepts-and-interview-questions-04f69c408e81
- https://code.likeagirl.io/cte-vs-subquery-vs-recursive-cte-the-interview-question-every-data-scientist-should-know-ce6163487841
- https://www.youtube.com/watch?v=Hv54WLTHN70
- https://www.red-gate.com/simple-talk/databases/sql-server/t-sql-programming-sql-server/questions-about-cube-rollup-and-grouping-sets-that-you-were-too-shy-to-ask/
- https://towardsdatascience.com/sql-explained-grouping-sets-rollup-and-cube-a097456fb9a2/
- https://cwiki.apache.org/confluence/display/Hive/Enhanced+Aggregation%2C+Cube%2C+Grouping+and+Rollup
- https://learnsql.com/blog/group-by-sql-interview-questions/
- https://blog.dailydoseofds.com/p/grouping-sets-rollup-and-cube-in
- https://www.youtube.com/watch?v=HTemHu1o4Qs
- https://www.reddit.com/r/SQL/comments/u30iqg/sql_interview_tips_creative_use_of_sql_time/
- https://medium.com/coding-odyssey/sql-joins-deep-dive-with-interview-questions-b0d64a5670a8
- https://www.crunchydata.com/developers/playground/lateral-join
- https://medium.com/@goldengrisha/a-deep-dive-into-sql-lateral-join-7b09fcb3b745
- https://www.youtube.com/watch?v=NiiN63lEzvI
- https://www.youtube.com/watch?v=EgW3fHqeBNM