Company: BlackRock
CTC: 26LPA
Source: Linked Post
Solution:
SELECT AVG(salary) AS median_salary
FROM (
SELECT salary
FROM employees
ORDER BY salary
LIMIT 2 - (SELECT COUNT(*) FROM employees) % 2
OFFSET (SELECT (COUNT(*) - 1) / 2 FROM employees)
) subquery;
Explanation:
Here we need to find out the median salary from the employees
table. To calculate the median salary, we need some essential information, like the total number of employees in the table.
First, let’s understand what a median is. Median is the middle value in a sorted list of values.
To achieve this, we divide the logic into steps:
employees
table using COUNT(*)
.2 - (COUNT(*) % 2)
, we decide how many rows to fetch: COUNT % 2 = 1
), 2 - 1 = 1
→ Select 1 row.COUNT % 2 = 0
), 2 - 0 = 2
→ Select 2 rows.(COUNT(*) - 1) / 2
calculates how many rows to skip (offset) before reaching the middle. (9 - 1) / 2 = 4
→ Start at the 5th row.(10 - 1) / 2 = 4
→ Start at the 5th row.LIMIT
and OFFSET
based on the results of the calculations.AVG(salary)
in the outer query to compute the average of the rows returned by the subquery.COUNT(*)
).Hi, I am Vishal Jaiswal, I have about a decade of experience of working in MNCs like Genpact, Savista, Ingenious. Currently i am working in EXL as a senior quality analyst. Using my writing skills i want to share the experience i have gained and help as many as i can.
In this article, we’ve compiled 30 carefully selected multiple choice questions (MCQs) with answers to…
Welcome to Day 15 of our Python for Data Science journey!On Day 15, we dived…
Welcome to Day 14 of our Python for Data Science journey! Today, we explored Seaborn,…
Welcome to Day 13 of Learning Python for Data Science! Today, we’re focusing on three…
Test your understanding of Python Data Structure, which we learned in our previous lesson of…
Welcome to Day 12 of Learning Python for Data Science. Today, we’ll dive into Pandas,…