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으로 가져오고 싶은 행의 개수를 지정할 수 있다.
'데이터 분석 > SQL' 카테고리의 다른 글
| [day2] SQL - 상위 n개 데이터 구하기 'Limit' (0) | 2025.02.18 |
|---|---|
| [달리기반 SQL] 6번 문제 (0) | 2025.02.13 |
| [SQL] WHERE / HAVING 차이 정리 (0) | 2025.02.13 |
| [달리기반 SQL] 4번 문제 (0) | 2025.02.12 |
| [엑셀보다 빠른 SQL] 5-5 Window 함수 (이거 다시 풀어봐야 함) (0) | 2025.02.11 |