Post

퀘스트 - 걷기반 마지막 연습 문제!

퀘스트 - 걷기반 마지막 연습 문제!

문제

다음과 같은 상품(products) 테이블과 주문(orders) 테이블이 있습니다.

  • products 테이블
idnameprice
1랩톱1200
2핸드폰800
3타블렛400
  • orders 테이블
idproduct_idquantityorder_date
101122023-03-01
102212023-03-02
103352023-03-04

44. 모든 주문의 주문 ID와 주문된 상품의 이름을 나열하는 쿼리를 작성해주세요!
45. 총 매출(price * quantity의 합)이 가장 높은 상품의 ID와 해당 상품의 총 매출을 가져오는 쿼리를 작성해주세요!
46. 각 상품 ID별로 판매된 총 수량(quantity)을 계산하는 쿼리를 작성해주세요!
47. 2023년 3월 3일 이후에 주문된 모든 상품의 이름을 나열하는 쿼리를 작성해주세요!
48. 가장 많이 판매된 상품의 이름을 찾는 쿼리를 작성해주세요!
49. 각 상품 ID별로 평균 주문 수량을 계산하는 쿼리를 작성해주세요!
50. 판매되지 않은 상품의 ID와 이름을 찾는 쿼리를 작성해주세요!




문제 풀이

44. 모든 주문의 주문 ID와 주문된 상품의 이름을 나열하는 쿼리를 작성해주세요!

1
2
3
select o.id,
       p.name
from order o join products p on o.product_id=p.id;
  • JOIN만 쓸 경우 INNER JOIN과 동일하게 작동합니다


45. 총 매출(price * quantity의 합)이 가장 높은 상품의 ID와 해당 상품의 총 매출을 가져오는 쿼리를 작성해주세요!

1
2
3
4
5
6
select p.id,
       sum(p.price*o.quantity) total_sales
from orders o inner join products p on o.product_id=p.id
group by p.id
order by total_sales desc
limit 1


46. 각 상품 ID별로 판매된 총 수량(quantity)을 계산하는 쿼리를 작성해주세요!

1
2
3
4
select p.id,
       sum(o.quantity) total_quantity
from products p inner join orders o on p.id=orders.product_id
group by p.id;


47. 2023년 3월 3일 이후에 주문된 모든 상품의 이름을 나열하는 쿼리를 작성해주세요!

1
2
3
select p.name
from products p inner join orders o on p.id=orders.product_id
where o.order_date>='2023-03-03';


48. 가장 많이 판매된 상품의 이름을 찾는 쿼리를 작성해주세요!

1
2
3
4
5
select p.name,
       sum(o.quantity) total_quantity
from products p inner join orders o on p.id=o.product_id
order by total_quantity desc
limit 1;


49. 각 상품 ID별로 평균 주문 수량을 계산하는 쿼리를 작성해주세요!

1
2
3
4
select p.id,
       avg(o.quantity) avg_quantity
from products p inner join orders o on p.id=o.product_id
group by p.id;


50. 판매되지 않은 상품의 ID와 이름을 찾는 쿼리를 작성해주세요!

1
2
3
4
select p.id,
       p.name
from products p left join orders o
where o.id is null;
This post is licensed under CC BY 4.0 by the author.