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.
SQL Interview Question at Zomato: These questions were recently asked in interview at Zomato, you…
Introduction: SQL Indexing and Query Optimization SQL indexing is a critical concept that can drastically…
This article is about the SQL Interview Questions asked by Walmart for their Data Analyst…
You must be able to answer these SQL Interview Questions if you are applying for…
This article tackles common SQL Interview Questions asked by EY, offering detailed solutions and explanations…
1164. Product Price at a Given Date: Learn how to track and select price from…