SQL & Pandas Challenge 3 Solution
SQL & Pandas Challenge 3 Solution
SQL & Pandas Challenge 3 Solution
CHALLENGE-3
http://www.linkedin.com/in/pmpraveen802
Question
Table: Employee
+--------------------+--------+
| Column Name | Type |
+--------------------+--------+
| id | int |
| salary | int |
+--------------------+--------+
id is the primary key (column with unique values) for this table.
Each row of this table contains information about the salary of an employee.
Continued…
Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null.
The result format is in the following example.
Example 1:
Output 1:
Input: Employee
Example 2:
Output 2:
Input: Employee
Query for the input table
-- Example 1:
CREATE TABLE Employee (
id INT PRIMARY KEY,
salary INT
);
SELECT
(SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary;
Solution using MySQL
Solution using CTE and IFNULL
WITH cte AS
(
SELECT *
, DENSE_RANK() OVER(ORDER BY salary DESC) AS rn
FROM employee
)
SELECT IFNULL(
(SELECT salary
FROM cte
WHERE rn = 2
LIMIT 1), NULL) AS SecondHighestSalary ;
Solution using MySQL
Solution using CTE and COALESCE
/* Even COALESCE can also be used instead of IFNULL*/
WITH cte AS
(
SELECT *
, DENSE_RANK() OVER(ORDER BY salary DESC) AS rn
FROM employee
)
SELECT COALESCE(
(SELECT salary
FROM cte
WHERE rn = 2
LIMIT 1), NULL) AS SecondHighestSalary;
Solution using Python(Pandas)
import pandas as pd
print("\nExample 2:")
print("Second Highest Salary:", result2)
LET'S
CONNECT
PRAVEEN KUMAR MAURYA
https://www.linkedin.com/in/pmpraveen802