Leetcode SQL (#181 – #185)

181. Employees Earning More Than Their Managers

Question:

https://leetcode.com/problems/employees-earning-more-than-their-managers/

Solution:

select 
employee
from(
    select 
        e.Name as employee, 
        e.salary, 
        e.managerid, 
        ifnull(m.salary,0) as manager_salary
    from employee e
        left join employee m 
            on e.managerid = m.id
    where e.salary > m.salary
) e

182. Duplicate Emails

Question:

https://leetcode.com/problems/duplicate-emails/

Solution:

select 
distinct e.email
from(
    select 
    email, 
    count(email) over(partition by lower(email) ) as cnt
    from person
) e
where e.cnt > 1

183. Customers Who Never Order

Question:

https://leetcode.com/problems/customers-who-never-order/

Solution:

select 
name as customers
from customers 
where Id not in (
    select 
    customerid 
    from orders 
    group by 1
) 

184. Department Highest Salary

Question:

https://leetcode.com/problems/department-highest-salary/

Solution:

select 
a.department, 
a.employee, 
a.salary
from(
    select 
    d.name as department, 
    e.name as employee, 
    ifnull(e.salary,0) as salary,
    max(ifnull(e.salary,0)) over(partition by d.name order by ifnull(e.salary,0) desc) as max_salary
    from department d
        join employee e 
            on e.departmentid = d.id
    order by d.id
) a
where a.salary = a.max_salary

185. Department Top Three Salaries

Question:

https://leetcode.com/problems/department-top-three-salaries/

Solution:

select 
d.name as department, 
e.employee, 
e.salary
from(
    select 
    departmentid, 
    name as employee, 
    salary,
    dense_rank() over(partition by departmentid order by salary desc) as r
    from employee
) e
join department d 
    on e.departmentid = d.id
where e.r <= 3