SQL Window Function Interview Question: Ranking Problem

SQL is the most important skill for a data science/analytics professional and during the interviews, SQL window function problems are always the interviewer’s favorite. Mastering window functions will play a key role in your job interview success.

Let us first take a look at the types of window functions available in SQL:

  • Aggregate Window Functions: SUM(), MAX(), MIN(), AVG(). COUNT()
  • Ranking Window Functions: ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(), CUME_DIST(), PERCENT_RANK()
  • Value Window Functions: LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE()

The OVER() clause differentiates the window functions from other functions in SQL. The OVER() clause defines the window of rows over which the window function is applied.

Now, let’s test yourself with a real SQL interview question.

Problem Statement: Find top 2 users with highest total order amount for each company

Write an SQL query to return top 2 users from each company that have the maximum total order amount (sum of all orders by user). Output should contain Company, User_Id and rank of the user. In case there are multiple users with the same rank then keep them all.

SQL Tables: Orders, Company

Orders

User_IdOrder_DateAmount
596221-Apr-20192
590003-Mar-20232
557331-Mar-20131
553209-Mar-20135
504530-Apr-20177
542120-Mar-20124
544314-Apr-20468
595813-Apr-20145
563723-Mar-20181
528509-Mar-20101
541727-Apr-20115
556619-Apr-20203
572317-Apr-20202
510527-Apr-20191
578118-Mar-20143
527801-Apr-20110
503716-Mar-20136
564108-Apr-20136
512103-Apr-20195
562710-Apr-20136
510512-Mar-20135
553206-Mar-20226
542104-Mar-20193
512131-Mar-20201
541713-Apr-20228
541715-Mar-20179
541712-Apr-20140
510530-Mar-20123
527829-Apr-20145
542121-Apr-20116
553217-Apr-20234
528519-Apr-20239
557305-Apr-20237
562722-Mar-20124
544319-Mar-20194
564117-Apr-20163
564110-Mar-20173
527824-Apr-20230
590010-Apr-20233
563713-Mar-20246
553210-Apr-20184

Company

UserIDCompany
5962Amazon
5900Amazon
5573Ebay
5532Amazon
5045Ebay
5421Ebay
5443Amazon
5958Ebay
5637Ebay
5285Flipkart
5417Amazon
5566Ebay
5723Ebay
5105Amazon
5781Ebay
5278Ebay
5037Ebay
5641Ebay
5121Flipkart
5627Amazon

Solution: Please check the below video

Let us know your thoughts in the comment section below. We will keep adding more SQL interview questions over time.

Leave a Reply

Your email address will not be published. Required fields are marked *