데이터 분석/SQL

[걷기반 SQL] 마지막 연습 문제 톺아보기

경 민 2025. 2. 12. 16:47

48. 가장 많이 판매된 상품의 이름을 찾는 쿼리


 

내가 작성한 쿼리

select p.name,
max(sum(o.quantity))
from
(
select p.name,
sum(o.quantity) total_sales
from orders o inner join products p on o.product_id = p.id
group by p.name
) a
group by 1

 

답안

SELECT p.name,
      SUM(o.quantity) AS total_quantity
FROM products p INNER JOIN orders o ON p.id = o.product_id
GROUP BY p.id
ORDER BY total_quantity DESC LIMIT 1;

 

 

🔶 배운 것

LIMIT으로 가져오고 싶은 행의 개수를 지정할 수 있다.