T_era
[MySQL] 문제풀이 : 가장 많이 팔린 품목은? 본문
더보기
문제:
Products 테이블:
|
ProductID
|
ProductName
|
Category
|
Price
|
|
1
|
Laptop
|
Electronics
|
1000
|
|
2
|
Smartphone
|
Electronics
|
800
|
|
3
|
Headphones
|
Electronics
|
150
|
|
4
|
Coffee Maker
|
Home
|
200
|
|
5
|
Blender
|
Home
|
100
|
Orders 테이블:
|
OrderID
|
ProductID
|
OrderDate
|
Quantity
|
CustomerID
|
|
101
|
1
|
2024-02-01
|
2
|
1
|
|
102
|
3
|
2024-02-02
|
1
|
2
|
|
103
|
2
|
2024-02-03
|
1
|
1
|
|
104
|
4
|
2024-02-04
|
3
|
3
|
|
105
|
1
|
2024-02-05
|
1
|
2
|
|
106
|
5
|
2024-02-06
|
2
|
3
|
Customers 테이블:
|
CustomerID
|
CustomerName
|
Country
|
|
1
|
Alice
|
USA
|
|
2
|
Bob
|
UK
|
|
3
|
Charlie
|
USA
|
요구사항:
1.
각 고객이 구매한 모든 제품의 총 금액을 계산하고, 고객 이름, 총 구매 금액, 주문 수를 출력하는 SQL 쿼리를 작성해주세요.
|
CustomerName
|
TotalAmount
|
OrderCount
|
|
Alice
|
2600
|
3
|
|
Bob
|
950
|
2
|
|
Charlie
|
800
|
2
|
더보기
select
c.CustomerName,
SUM(p.Price * o.Quantity) as TotalAmount,
COUNT(o.OrderID) as OrderCount
from Customers c
join Orders o on c.CustomerID = o.CustomerID
join Products p on o.ProductID = p.ProductID
group by c.CustomerName;
2.
각 제품 카테고리별로 가장 많이 팔린 제품의 이름과 총 판매량을 조회하는 SQL 쿼리를 작성해주세요.
|
Category
|
Top_Product
|
TotalSold
|
|
Electronics
|
Laptop
|
3
|
|
Home
|
Coffee Maker
|
3
|
더보기
with RankedProducts as (
select
p.Category,
p.ProductName,
sum(o.Quantity) as TotalSold,
row_number() over(partition by p.Category order by sum(o.Quantity) desc) as rank
from Products p
join Orders o on p.ProductID = o.ProductID
group by p.Category, p.ProductName
)
select
Category,
ProductName as Top_Product,
TotalSold
from RankedProducts
where rank = 1
* 2번문제에서 좀 오래 막혀서 ai에 도움을 받았다
처음보는 with as 가 나와서 찾아보니 임시Table을 만들어 사용하는 것이라 하더라
'Programing > Datababse' 카테고리의 다른 글
| SQL 언어 (0) | 2025.05.08 |
|---|---|
| [MySQL] 문제풀이 : 예산이 가장 큰 프로젝트는? (0) | 2025.03.25 |
| [MySQL] 문제풀이 : 가장 높은 월급을 받는 직원은? (0) | 2025.03.25 |
| [MySQL] 문제풀이 : 단골 고객님 찾기 (0) | 2025.03.25 |
| [MySQL] 문제풀이 : 이용자의 포인트 조회하기 (0) | 2025.03.25 |