SQL Window Function Interview Question: Employee Rating Difference

This is our second problem statement in the SQL Interview Questions series. In this series we are committed to bring out a collection of real world SQL interview questions, we have also shared the video solution for each question.

To check all the interview questions available in the series, click here.

SQL is a very important skill for the data science/analytics professionals and SQL window function problems are very frequently asked in the interviews. 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()

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

Problem Statement: Difference between the average rating and the second last rating of employees

Find the difference between the average rating and the second last rating of all the employees in the Employee table. Output the employee’s name, average rating, second last rating and the difference between the two ratings, output the rating difference up to 1 decimal place only.

SQL Table: Employee

Employee

EmpNameEmpIDDepartmentYearRating
PeterE5489Marketing20208
PeterE5489Marketing20197
PeterE5489Marketing20186.5
PeterE5489Marketing20178.5
PeterE5489Marketing20167
PhilipE1027HR20208
PhilipE1027HR20198.5
ShirleyE0589Finance20207
ShirleyE0589Finance20195
ShirleyE0589Finance20186
ShirleyE0589Finance20177
WilliamE4128Sales20208
WilliamE4128Sales20196.5
WilliamE4128Sales20187
JessicaE6987HR20209
JessicaE6987HR20199
JessicaE6987HR20188.5
JessicaE6987HR20178
MichaelE1128Admin20207
MichaelE1128Admin20198
MichaelE1128Admin20187.5
MichaelE1128Admin20176
MichaelE1128Admin20167
FrankE8879Finance20205
FrankE8879Finance20196
FrankE8879Finance20186
FrankE8879Finance20177
JenniferE5641Engineering20208
JenniferE5641Engineering20198
JenniferE5641Engineering20188

Solution: Please Check the below video

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

Leave a Reply

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