Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Amazon's Business Analyst Interview Question

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

create table department(

dept_id int,
dept_name varchar(25));

select * from department;

INSERT INTO department


VALUES
(1,'sales'),
(2,'marketing'),
(3,'operations'),
(4,'finance');

create table employee(


emp_id int,
emp_name varchar(25),
salary int,
dept_id int);

insert into employee


values
(1,'john',50000,1),
(2,'sarah',60000,2),
(3,'alice',55000,1),
(4,'bob',48000,3),
(5,'emma',52000,2),
(6,'mike',51000,3),
(7,'olivia',59000,4),
(8,'ethan',54000,4);

select * from employee;

Solution1
Note: This will not handle the situation when there is a tie between 2nd highest for two or more
than 2 department.

select e.dept_id,dept_name, avg(salary) as avg_salary


from employee e
join department d on d.dept_id = e.dept_id
group by e.dept_id,dept_name
order by avg_salary desc
limit 1 offset 1;
Solution2
select dept_name,dept_avg_sal from
(
select dept_name,dept_avg_sal,
dense_rank() over(order by dept_avg_sal desc) as rnk
from
(select dept_name,
avg(salary) over (partition by e.dept_id) dept_avg_sal
from employee e join department d on d.dept_id = e.dept_id
)t1
)t2
where rnk =2
group by dept_name,dept_avg_sal;

Solution3

with dept_avg as(


select dept_name,avg(e.salary) as avg_sal,
dense_rank() over(order by avg(e.salary) desc) as rnk
from department d
join employee e on e.dept_id = d.dept_id
group by d.dept_name)

select dept_name,avg_sal from dept_avg


where rnk = 2;

Solution4

with cte as(


select dept_name,
avg(salary) over (partition by e.dept_id) dept_avg_sal
from employee e join department d on d.dept_id = e.dept_id)

select dept_name,dept_avg_sal
from cte c1 where 2 =
(select count(distinct dept_avg_sal) from cte c2 where c2.dept_avg_sal >= c1.dept_avg_sal)
group by dept_name,dept_avg_sal;

You might also like