๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find employees who earn the same salary as at least one other employee in the same department.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
employee_id,
employee_name,
department,
salary
FROM employees
WHERE (department, salary) IN (
SELECT
department,
salary
FROM employees
GROUP BY department, salary
HAVING COUNT(*) > 1
)
ORDER BY department, salary DESC;
๐ก Explanation:
The query identifies duplicate salary values within each department.
โข The subquery groups records by department and salary.
โข **HAVING COUNT(*) > 1** finds salary values that appear more than once in the same department.
โข The outer query returns all employees whose (department, salary) matches those duplicate combinations.
This question tests your understanding of:
โ
GROUP BY
โ
HAVING
โ
Multi-column filtering
โ
Identifying duplicate records
๐ฏ Expected Output Example
Employee Department Salary
John IT 80,000
Alice IT 80,000
David HR 65,000
Sarah HR 65,000
๐ Alternative Using Window Functions
SELECT
employee_id,
employee_name,
department,
salary
FROM (
SELECT
*,
COUNT(*) OVER (
PARTITION BY department, salary
) AS salary_count
FROM employees
) t
WHERE salary_count > 1;
This approach avoids a subquery with GROUP BY and is a great way to showcase your knowledge of window functions.
๐ When interview questions ask you to find duplicates, think of these three approaches:
1. GROUP BY + HAVING
2. Window functions COUNT() OVER
3. Self Join for specific comparison scenarios
Knowing multiple solutions demonstrates strong SQL problem-solving skills.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2320
1.78K
- โค 6