SQL

Swapped Food Delivery: Zomato SQL Interview Question

sawo11 2025. 4. 24. 17:58

오늘부터 다시 코테 연습 시작!!

나는..취업할 수 있다......!🥹


문제 풀이 링크: https://datalemur.com/questions/sql-swapped-food-delivery

 

Zomato SQL Interview Question | DataLemur

Zomato SQL Interview Question: Write a query to correct the swapping food order error and return the proper pairing of order ID and item.

datalemur.com


🔹 해결해야 할 일:

  • 뒤바뀐 아이템들을 원래의 순서로 복원
  • 짝수/홀수 번호에 따라 아이템을 서로 교환
  • 마지막 주문이 홀수일 경우 → 짝이 없기 때문에 그대로 유지
WITH order_counts AS (
  SELECT COUNT(order_id) AS total_orders
  FROM orders
  )
  
SELECT 
	-- 홀수 번째는 + 1
    CASE WHEN order_id % 2 != 0 AND order_id != total_orders THEN order_id + 1 
    -- 마지막 순서는 그대로
    WHEN order_id % 2 != 0 AND order_id = total_orders THEN order_id 
    -- 짝수 번째는 - 1
    ELSE order_id - 1 
  END AS corrected_order_id,
  item
FROM orders
-- 전체 주문 수를 각 주문 행에 붙이기 위해 사용
CROSS JOIN order_counts 
ORDER BY corrected_order_id;