본문 바로가기
IT

SQL Quiz N번째 높은 급여 찾기

by 결국 그렇고 그런이야기 2021. 10. 19.
반응형

이 글은 가능하면 휴대폰보다는 컴퓨터로 보는 것이 가독성이 좋을 것이다.

공부하며 쓴 것이라 컴퓨터 크기에 맞추어져 있다.

 

오늘 Select query를 공부하다가 재미있는 문장을 발견해서 가져와 본다.

출처는 40가지 쿼리 인터뷰에서 가장 많이 나온다는 질문들 리스트이다.

기본적인 내용들이 대부분인데 이런걸 손으로 풀라고 하는 건지 아니면 테이블도 만들고 데이터도 만들어서

컴퓨터 하나주고 풀라고 하는지는 모르겠으나 흥미롭긴하다.

 

보다 자세한 내용은 아래 자료 참조.

 

40 SQL Query Interview Questions and Answers You Must Practice (artoftesting.com)

 

Ques.40. Write SQL query to find the 3rd highest salary from a table without using the TOP/limit keyword.
Ans. This is one of the most commonly asked interview questions. For this, we will use a correlated subquery.

In order to find the 3rd highest salary, we will find the salary value until the inner query returns a count of 2 rows having the salary greater than other distinct salaries.

 

3번째 높은 급여를 찾으라는 건데.

간단한 테이블 생성 및 데이터는 아래와 같이 했다.

 

 

-- Table: public.employeesalary

-- DROP TABLE public.employeesalary;

CREATE TABLE IF NOT EXISTS public.employeesalary
(
    empld character varying(5) COLLATE pg_catalog."default",
    project character varying(5) COLLATE pg_catalog."default",
    salary integer,
    variable character varying(10) COLLATE pg_catalog."default"
)

TABLESPACE pg_default;

ALTER TABLE public.employeesalary
    OWNER to postgres;

 

INSERT INTO public.employeesalary(empld, project, salary, variable) VALUES ('121', 'P1',8000 ,'500' );
INSERT INTO public.employeesalary(empld, project, salary, variable) VALUES ('321', 'P2',10000 ,'1000' );
INSERT INTO public.employeesalary(empld, project, salary, variable) VALUES ('421', 'P1',12000 ,'0' );

 

 

 

일단 본문에 나온 설명은 오답이다.

정답은 self join 활용하여 부등호 뿐만 아니라 equal(=) 도 필요하다.

 

SELECT Salary
      FROM public.EmployeeSalary Emp1
     WHERE 3 = ( //아래에 조건은 >=로 하면 몇번째 높은 급여를 알고 싶은지 바로 숫자 넣으면 된다.
                SELECT COUNT(DISTINCT(Emp2.Salary))
                  FROM public.EmployeeSalary Emp2
                 WHERE Emp2.Salary >= Emp1.Salary
               )

 

단순하게 제일 높은 급여를 받는 사람은 아래와 같이도 짤 수 있다.

 

SELECT *
FROM EmployeeSalary
ORDER BY Salary DESC LIMIT 1;

 

이때는 근데 중요한게 Salary 컬럼이 integer(int) 형이고 숫자로 저장되어 있어야만 정확한 비교가 가능하다..

반응형

댓글