MS-SQL문 강좌 3 장
select sum(qty) from sales -- sales 의 qty값의 합계를 구함
select avg(qty), max(qty), min(qty) from sales -- qty의 평균과 최고값, 최소값을 구함
select count(*) from titles -- titles 테이블의 갯수를 구함
select count(title_id) from titles -- title_id 갯수를 구한다 (null 값이 있을 경우 카운트 안함-카운트의 경우)
select price, isnull(price, 0) as price_after from titles -- 널값을 isnull을 사용하여 0으로 나타나게 함
select title_id, qty
from sales
order by title_id -- title_id로 정렬
select title_id, sum(qty) as SumValue
from sales
where qty >=30 -- 30 이상을 추출한뒤
group by title_id
having sum(qty) >=50 --그룹에서 50이상만 다시 추출
order by title_id
select title_id, sum(qty) as SumValue -- 집계함수를 사용해야만이 group by 명령어를 쓸수 있음
from sales
group by title_id -- 그룹별로 정렬 출력
having sum(qty)>=30 -- group by와 항상 같이 쓰이며 SumValue값이 30보다 크거나 같은값이 출력
order by title_id -- group by 앞에 order by 는 올 수 없음
select title_id, sum(qty) as SumValue
from sales
where qty >=30
group by all title_id --group by를 사용하여 탈락된 title_id(null값으로 표시)를 표시하라는 명령
select type, avg(price) as PriceAverage --price의 평균을 구함(일반적)
from titles
group by type
select type, price
from titles
order by type -- order by 다음에는 compute를 쓸 수 있다
compute avg(price) by type -- compute by 를 사용하여 type에 대해 그룹지어진 뒤 price의 평균값을 구한다
compute avg(price) -- by 절을 삭제함으로써 총 평균을 구할 수 있다
select a, b, qty -- 테스트 문제
from title
order by a,b
compute avg(qty) by a, b -- a와 b 순서가 바뀌면 안됨.(부분집합 지켜져야함)
compute avg(qty) by a
compute ave(qty)
select type, pub_id, price
from titles
order by type, pub_id
select type, pub_id, avg(price) as AveragePrice
from titles
group by type, pub_id
order by type, pub_id
select type, pub_id, avg(price) as AveragePrice -- 오른쪽(pub_id)에서 왼쪽으로 계산
from titles
group by type, pub_id with rollup --with rollup 명령으로 type에 대한, pub_id에 대한 각각의 AveragePrice를 구한다
order by type, pub_id -- 마지막 행에는 총계를 구해준다.(with rollup의 기능)
select type, pub_id, avg(price) as Average
from titles
group by type, pub_id with cube -- cube는 왼쪽(type)에서 오른쪽으로 계산표시되며, 표시되지 않았던 사항까지도 표시
order by type, pub_id
select title, price, pub_name
from titles join publishers -- titles와 phblisher을 조인한다
on titles.pub_id = publishers.pub_id --titles의 pub_id와 publishers의 pub_id를 조인한다.
select title, price, pub_name
from titles t join publishers p -- 두 테이블 조인시 변수명 t와 p를 설정해준다.
on t.pub_id = p.pub_id
select title, price, qty, pub_name, stor_name as 상점이름 -- stor_name 추가
from titles t join publishers p
on t.pub_id=p.pub_id
join sales s --3번째 테이블 조인
on s.title_id= t.title_id -- 키 값이 같은 title_id 사용하여 조인
join stores st -- stores 테이블 st 변수 지정
on s.stor_id= st.stor_id --sales 와 stores 테이블에 stor_id가 같으므로 조인
select title, price, pub_name
from titles cross join publishers -- cross 명령은 별로 의미 없는 데이터를 끌어내나, 성능향상에 도움이 될 수 있다
select title, qty
from titles t join sales s on t.title_id = s.title_id
select *
from titles where price is null --null 값만 출력
select title, qty
from titles t left outer join sales s -- 왼쪽(titles)테이블에서 모두 뽑아온다(null 값까지 넘어옴)
on t.title_id=s.title_id
where qty is null -- 수량이 null 인 값만 출력 (팔리지 않은 책만 출력)