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_Id | Order_Date | Amount |
---|---|---|
5962 | 21-Apr-20 | 192 |
5900 | 03-Mar-20 | 232 |
5573 | 31-Mar-20 | 131 |
5532 | 09-Mar-20 | 135 |
5045 | 30-Apr-20 | 177 |
5421 | 20-Mar-20 | 124 |
5443 | 14-Apr-20 | 468 |
5958 | 13-Apr-20 | 145 |
5637 | 23-Mar-20 | 181 |
5285 | 09-Mar-20 | 101 |
5417 | 27-Apr-20 | 115 |
5566 | 19-Apr-20 | 203 |
5723 | 17-Apr-20 | 202 |
5105 | 27-Apr-20 | 191 |
5781 | 18-Mar-20 | 143 |
5278 | 01-Apr-20 | 110 |
5037 | 16-Mar-20 | 136 |
5641 | 08-Apr-20 | 136 |
5121 | 03-Apr-20 | 195 |
5627 | 10-Apr-20 | 136 |
5105 | 12-Mar-20 | 135 |
5532 | 06-Mar-20 | 226 |
5421 | 04-Mar-20 | 193 |
5121 | 31-Mar-20 | 201 |
5417 | 13-Apr-20 | 228 |
5417 | 15-Mar-20 | 179 |
5417 | 12-Apr-20 | 140 |
5105 | 30-Mar-20 | 123 |
5278 | 29-Apr-20 | 145 |
5421 | 21-Apr-20 | 116 |
5532 | 17-Apr-20 | 234 |
5285 | 19-Apr-20 | 239 |
5573 | 05-Apr-20 | 237 |
5627 | 22-Mar-20 | 124 |
5443 | 19-Mar-20 | 194 |
5641 | 17-Apr-20 | 163 |
5641 | 10-Mar-20 | 173 |
5278 | 24-Apr-20 | 230 |
5900 | 10-Apr-20 | 233 |
5637 | 13-Mar-20 | 246 |
5532 | 10-Apr-20 | 184 |
Company
UserID | Company |
---|---|
5962 | Amazon |
5900 | Amazon |
5573 | Ebay |
5532 | Amazon |
5045 | Ebay |
5421 | Ebay |
5443 | Amazon |
5958 | Ebay |
5637 | Ebay |
5285 | Flipkart |
5417 | Amazon |
5566 | Ebay |
5723 | Ebay |
5105 | Amazon |
5781 | Ebay |
5278 | Ebay |
5037 | Ebay |
5641 | Ebay |
5121 | Flipkart |
5627 | Amazon |
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.