4월 18일
100점
기한: 4월 18일
.sql 파일을 제출하시오.
수업 댓글
내 과제
제출함
0418박강원.sql
SQL
비공개 댓글
--집합연산
--합집합, 차집합, 교집합
--사실은... 데이터베이스의 테이블로 어떠한 데이터들의 집합 즉, 테이블=집합
--그러면... 테이블에 집합연산을 할 순 없을까?
--합집합 : UNION, 차집합: MINUS, 교집합: INTERSECT
select * from customer;
select * from book;
select * from orders;
--customer 테이블에는 도서를 주문한 고객과 주문하지 않은 고객이 함께 있다. 그 중 도서를 주문하지 않은 고객의 이름을 구하시오
--1단계 orders 테이블에서 고객번호 모두 추출하기
select custid
from orders;
--2단계 1단계에서 추출한 고객번호에 없는 (not in) customer 테이블의 고객 추출하기
select name
from customer
where custid not in(1,2,3,4);
--다른방법
select name
from customer
where custid not in(select custid
from orders);
--풀이방법 2. 집합연산 minus 활용
--도서를 주문하지 않은 고객의 이름
--(도서를 주문하지 않은 고객)=(모든 고객)-(도서를 주문한 고객)
--1단계 모든 고객 집합(테이블)구하기
select *
from customer;
--2단계 도서를 주문한 고객의 집합 구하기
select name
from customer
where custid in(select custid
from orders);
--3단계 minus하기
select*
from customer
minus
select *
from customer
where custid in(select custid
from orders);
--분석!! 위의 집합 minus 아래 집합
--결론!! 집합얀산은 잘 안쓴다!(이런 부분이 있네~? 하고 패스)
--Q1. 마당서점(지금 데이터베이스 = 마당) 도서의 총 개수
select count(bookid)
from book;
--Q2. 마당서점에 도서를 출고하는 출판사 개수
select count(DISTINCT publisher)
from book;
--Q3. 2020 7월 4일 ~7월 7일 사이 주문받은 도서의 주문번호
select custid
from orders
where orderdate between '20200701' and '20200706';
--Q4. 성이 '김'씨인 고객의 이름과 주소
select name, address
from customer
where name like'김%';
--Q5. 성이 '김'씨 마지막 '아'인 이름을 가진 고객의 이름과 주소
select name, address
from customer
where name like'김%아';
--Q6.주문금액의 총액과 주문의 평균금액
select sum(saleprice), avg(saleprice)
from orders;
--Q7. 고객의 이름과 고객별 구매액(단, 구매액이 높은 순으로 나열하시오)
select name, sum(saleprice)
from orders o, customer c
where o.custid = c.custid
group by name
order by sum(saleprice) desc;
--Q8.도서의 가격(북테이블)과 판매가격(orders 테이블)의 차이가 가장 큰 값을 출력하시오
select max(price - saleprice)
from book b, orders o
where o.bookid = b.bookid;
--전체 출력한다면
select price - saleprice
from book b, orders o
where o.bookid = b.bookid;