[SQL] LeetCode 문제풀이 (#627, #1050, #1068, #1075, #1084)

Jinyoung Cheon·2026년 4월 27일

LeetCode

목록 보기
6/9

627. Swap Sex of Employees

문제 설명

Write a solution to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a single update statement and no intermediate temporary tables.

Note that you must write a single update statement, do not write any select statement for this problem.

sex가 'f'인 값을 'm'으로 변경하고, 'm'인 값은 'f'로 변경하는 문제입니다.
SELECT가 아닌 UPDATE를 사용해야합니다.

UPDATE Salary
SET sex = CASE 
    WHEN sex = 'm' THEN 'f'
    ELSE 'm'
    END;

UPDATE는 처음 사용해봤기 때문에 내용을 좀 찾아 정리했습니다.

기본문법구조

UPDATE 테이블명
SET 컬럼명1 = 변경할값1, 컬럼명2 = 변경할값2
WHERE 조건;

UPDATE를 활용할 때에는 WHERE구문을 잘 활용하는 것이 중요합니다. 실행 전, 먼저 SELECT * FROM 테이블명 WHERE 조건;을 실행 후 내가 수정하려는 대상이 정확히 의도한 데이터인지 확인하는 습관이 필요할 것 같습니다.

1050. Actors and Directors Who Cooperated At Least Three Times

문제설명

Write a solution to find all the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times.

Return the result table in any order.

(actor_id, director_id) 쌍의 같이 작업한 횟수가 최소 3개 이상인 조합을 찾아내면 되는 문제입니다.

SELECT actor_id, director_id

FROM ActorDirector

GROUP BY actor_id, director_id

HAVING COUNT(*) >= 3

easy하게 풀 수 있는 문제였다.

1068. Product Sales Analysis I

문제설명

Write a solution to report the product_name, year, and price for each sale_id in the Sales table.

Return the resulting table in any order.

두 테이블을 JOIN해서 해당하는 컬럼들을 추출하는 문제입니다.

SELECT 
    p.product_name,
    s.year,
    s.price
FROM Sales s
JOIN Product p
ON s.product_id = p.product_id

이정도는 너무 easy합니다

1075. Project Employees I

문제설명

Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.

Return the result table in any order.

프로젝트 별로 참여한 employee들의 experience years의 평균을 소수점 둘째자리까지 나타내는 문제입니다.

-- 프로젝트 별 참여한 근로자들의 평균 경험 연도 추출
SELECT 
    p.project_id,
    ROUND(AVG(experience_years), 2) as average_years
FROM Project p 
LEFT JOIN Employee e
ON p.employee_id = e.employee_id

GROUP BY p.project_id

일단 문제에서 ~별로 이런게 나오면 GROUPBY를 활용한다.
처음에는 SUM(e.experience_years)/COUNT(e.experience_years)를 사용했지만 AVG 함수가 있었지.. 아직도 효율적으로, 빠르게 생각이 안나는걸 보니 SQL 연습 아직 멀었다!!!!
아직은 Easy 난이도의 문제만 풀고 있지만 Median, Hard까지 열심히 가보자. 🔥🔥

1084. Sales Analysis III

문제설명

Write a solution to report the products that were only sold in the first quarter of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

Return the result table in any order.

1분기에만 팔린 product_id와 product_name을 추출하는 문제입니다.
처음에 작성한 쿼리는 다음과 같습니다.

SELECT 
    p.product_id,
    p.product_name
FROM Sales s
JOIN Product p
ON s.product_id = p.product_id

WHERE DATE(s.sale_date) BETWEEN DATE('2019-01-01') AND DATE('2019-03-31')+1
GROUP BY s.product_id
HAVING COUNT(s.product_id) = 1

[내가 겪은 문제점]

처음에는 WHERE 절을 사용해 2019년 1분기(1월~3월) 데이터만 필터링한 뒤, COUNT()를 이용해 판별하려고 했습니다. 하지만 이 방식은 치명적인 논리적 오류를 가지고 있었습니다.

[원인 분석: SQL 실행 순서]
SQL은 FROM → WHERE → GROUP BY → HAVING 순서로 실행됩니다.
만약 어떤 상품(product_id = 2)이 2월(1분기)과 6월(2분기)에 모두 팔렸다면, WHERE 절에서 6월 판매 기록이 먼저 삭제(필터링)되어 버립니다.
그 결과, GROUP BY 단계로 넘어갈 때는 2월 판매 기록만 남게 되고, HAVING COUNT() = 1이라는 조건마저 통과해버려서 1분기에만 팔린 상품으로 잘못 분류되는 문제가 발생한 것입니다.

seller_idproduct_idbuyer_idsale_datequantityprice
1112019-01-2122000
1222019-02-171800
2232019-06-021800
3342019-05-1322800

해결 방법: HAVING 절과 MIN/MAX의 활용 (정답 접근법)

WHERE 절에서 미리 데이터를 잘라내면 안 됩니다. 상품의 전체 판매 이력을 온전히 유지한 채로 그룹화(GROUP BY)를 진행해야 해당 상품이 언제 팔렸는지 정확히 검증할 수 있습니다.

[MIN과 MAX를 이용한 논리]

그룹화된 전체 데이터에서 조건 검사를 하기 위해 HAVING 절을 사용했습니다. 어떤 상품이 '오직 1분기에만' 팔렸다는 것을 증명하려면 다음 두 가지 조건이 모두 만족해야 합니다.

MIN(sale_date) >= '2019-01-01': 해당 상품의 가장 첫 판매일이 1월 1일 이후여야 한다. (이전 년도 판매 방지)

MAX(sale_date) <= '2019-03-31': 해당 상품의 가장 마지막 판매일이 3월 31일 이전이어야 한다. (2분기 이후 판매 방지)

profile
데이터를 향해, 한 걸음씩 천천히.

0개의 댓글