[문제] 모든 도서에 대해 결제금액(PAID)과 미결제금액(DUE)을 구하시오

image.png

image.png

정답

select title,
  round(sum(case when paid_date is not null then line_total else 0 end)) due,
  round(sum(case when paid_date is null then line_total else 0 end))  paid
from book_order_items boi
     join book_orders bo on boi.order_id= bo.id
     join books b on boi.book_id= b.id
group by title
order by title

풀이

  1. 모든 테이블 합치기
select bo.*
from book_order_items boi
     join book_orders bo on boi.order_id= bo.id
     join books b on boi.book_id= b.id

주의!! 테이블 3개를 합칠 때 부터 join과 on을 사용하는 방법이 계속 헷갈림!!

  1. 결제금액과 미결재금액 합치기
select title,
  round(sum(case when paid_date is not null then line_total else 0 end)) due,
  round(sum(case when paid_date is null then line_total else 0 end))  paid