Q1. 각 고객이 구매한 모든 제품의 총 금액을 계산하고, 고객 이름, 총 구매 금액, 주문 수를 출력
방법1. 내가 작성한 쿼리
1단계 : 모든 주문 건에 대해 고객 정보 연결 (customers, orders JOIN)
2단계 : 1단계에서 생성된 테이블과 Products 테이블 JOIN
3단계 : 원하는 값 추출
select a.customername,
sum(p.price * a.quantity) as TotalAmount,
count(a.orderid) as OrderCount
from products p inner join
(
select c.customerid,
CustomerName,
productid,
quantity,
OrderID
from customers c inner join orders o on c.customerid = o.customerid
) a on p.productid = a.productid
group by 1
order by 1
방법2. 깔끔하게 모든 데이터 JOIN 시키기
굳이 SELECT 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
order by 1
Q2. 각 제품 카테고리별로 가장 많이 팔린 제품의 이름과 총 판매량을 조회
1단계 : 카테고리별 제품의 이름과 총 판매량을 구하는 테이블 생성
2단계 : 그 중에서 '가장 많이 팔린 제품'이라는 조건을 걸어줌
3단계 : max값을 구하기 위한 서브쿼리 생성
select p.category,
p.ProductName,
sum(o.quantity)
from products p inner join orders o on p.ProductID = o.ProductID
group by 1,2
having
sum(o.quantity) =
(
select max(total_quan)
from
(
select category ,
o2.ProductID ,
sum(o2.Quantity) total_quan
from products p2 join orders o2 on p2.productid = o2.ProductID
group by 1,2
) a
where a.category = p.category
)
'데이터 분석 > SQL' 카테고리의 다른 글
| [day3] LIKE 문에서 대소문자 구분하기 (0) | 2025.02.19 |
|---|---|
| [day2] SQL - 상위 n개 데이터 구하기 'Limit' (0) | 2025.02.18 |
| [SQL] WHERE / HAVING 차이 정리 (0) | 2025.02.13 |
| [달리기반 SQL] 4번 문제 (0) | 2025.02.12 |
| [걷기반 SQL] 마지막 연습 문제 톺아보기 (0) | 2025.02.12 |