본문 바로가기

SQL/MS-SQL

My-SQL 연산함수/ISNULL/group by/compute

/* p.139 ~  */

select sum(qty) from sales;

-- 함수정리)

-- AVG() : 평균
-- COUNT() : 개수
-- COUNT(*) : 선택된 모든 행의 개수
-- MAX() : 가장 큰 값
-- MIN() : 가장 작은 값
-- SUM() : 합계

Select max(qty), min(qty) from sales;

Select count(*) from titles;

Select count(title_id) from titles;

Select count(price) from titles;
Select count(*) from titles where price is not null;
        수치 데이터에 NULL이 있을 때는 NULL 데이터(행)은 연산 함수의 대상에 제외된다.

Select sum(price), count(*), count(price) from titles;

Select sum(price)/ count(*) from titles;

Select sum(price) / count(price) from titles;
Select avg(price) from titles;


/*    ISNULL    */


select avg(isnull(price, 0)) from pubs..titles;

select avg(price) from pubs..titles;

select price, isnull(price, 0) from pubs..titles;

select price, isnull(price, 0) from titles;

select price, isnull(price, 0) from dbo.titles;

select price, isnull(price, 0) from pubs.dbo.titles;

-- 테이블 표현 방식이 여러가지가 있는 것을 유의하시기를 바랍니다. (이승호 강사)


/* SET ANSI Warning OFF  */

set ANSI_warnings off

select avg(price) from titles;


set ANSI_warnings on

select avg(price) from titles;

-- 두번째 것은 다음과 같은 메세지가 출력됩니다.

-- (1개 행 적용됨)  경고: 집계 또는 다른 SET 연산에 의해 Null 값이 제거되었습니다.


/*  Group By / Having  */


--  여러 권의 책이 팔린 경우 책의 번호에 따라 판매량(합)을 알고 싶다면.......Group By title_id


select title_id, sum(qty) as 'sum of qty' from sales group by title_id;

select title_id, sum(qty) as sum of qty from sales group by title_id; -- 물론 이러한 경우는 에러가 난다.

select title_id, sum(qty) as 'sum_of_qty' from sales group by title_id;

select title_id, sum(qty) as sum_of_qty from sales group by title_id;

-- sum_of_day 이런 식으로 '_' 을 첨부할 경우는 'sum_of_day'라고 표기한 결과와 동일하다( 이승호 강사)

-- 위에 언급한 두번째줄과 같이 실행하면 에러가 난다. 띄어쓰기가 들어가는 경우 반드시 ' '(작은 따옴표)를 넣어야 한다.

-- 물론 " "(큰 따옴표)를 표기하더라도 에러없이 잘되지만 다른 DB와의 호환성을 고려하여 가급적 ' '(작은 따옴표)를 사용하자.

-- 또한 살짝 드리는 얘기지만 원래 select * from titles; 라는 구문에서 각 필드나 테이블들도 사실은 " "을 붙일 수 있다.

-- 그러나 JSP 등에서의 연동과 또한 문자열들과의 혼동을 막기 위해 필드나 테이블 등에 원래 " "을 사용할 수 있지만 지양하도록 한다.

-- 대부분의 교재나 다른 강좌 등에서도 관례적으로 컬럼 필드들에는 " " 등을 표기 하지 않을 것이다. (이승호 강사)


-- 만약 위와 같은 조건에서 30권 이상의 책을 판매한 경우만 가져오고자 한다면.....????

select title_id, sum(qty) as 'sum of qty'
from sales
group by title_id
having sum(qty) >= 30


select title_id, sum(qty) as 'sum of qty'
from sales
where qty > 20
group by title_id
having sum(qty) >= 30


/*     Group By All     */


-- group by를 사용하면 where 절에서 제외된 것이라고 할지라도 결과에 포함시킬 수 있다. 한마디로 where을 살짝(?!) 무시하는 효과가 나타난다.

-- (이승호 강사)

select title_id, sum(qty) as 'sum of qty'
from sales
where qty > 40
group by all title_id


-- 교과서에 따르면 set dateformat 'ymd' 가 필요하다면 실행하도록 권장하네요.

-- select ord_date from sales;


select title_id, sum(qty) as 'sum of qty'
from sales
where ord_date between '94.1.1' and '94.12.31'
group by all title_id;


-- ANSI SQL과 T-SQL의 차이는 교과서와 사이트에 개재한 글을 보시면 약간의 경우를 알 수 있습니다.


/* compute / compute by  */


-- 상세 내역을 볼 수 없는 group by의 약점을 보완하는 compute는 상세내역과 그룹 합계를 한꺼번에 볼 수 있습니다.

select type, avg(price)
from titles
group by type;

-- 그렇다면 compute 를 돌려보자!

select type, title_id, price
from titles
order by type
compute avg(price) by type;

-- type 별로 평균이 구해지는 것을 알 수 있다.


-- 전체 평균을 얻기 위해서는 compute 만을 사용~~~~

select type, title_id, price
from titles
compute avg(price)

-- compute만을 사용할 때는 order by가 없어도 된다.

-- (중요!!) compute by 를 사용하려면 order by 가 compute by 앞에 반드시 와야만 하고, 또 order  by에서 지정된 순서대로,

-- 또는 일부분의 순서대로 compute by를 사용해야 한다.


/*------  염두해 두어야 할 예제 ---------*/


select type, pub_id, title_id, price

from titles

order by type, pub_id,  title_id

compute avg(price) by type, pub_id


-- 그런데 이게 왠일인가? 다음의 문장은 수행될 수 없다.

-- 이 두 구문(위 구문과 아래의 구문들)은 서로 비교할 때도 상당히 헷갈리는 부분이기 때문에 제대로 표시해 두시기를 바랍니다!!! (이승호 강사)


select type, pub_id, title_id, price

from titles

order by type, pub_id, title_id

compute avg(price) by pub_id, type;

-- 에러 발생 !

-- COMPUTE BY 목록이 ORDER BY 목록과 일치하지 않습니다.

-- 잘 보시면 order by에 들어가는 필드의 순서와 compute by에 들어가는 구문의 순서가 같으면 YES~! 다르면 NO~! 의 결과가 나옵니다.

-- 물론 위의 실행되는 구문에서 order by 뒤의 title_id를 빼더라도 문제 없이 돌아가죠.


-- 그런데.....

select type, pub_id, title_id, price

from titles

order by type, pub_id, title_id

compute avg(price) by title_id;

-- 돌려보면~ oops~! 역시 같은 결과입니다.

-- COMPUTE BY 목록이 ORDER BY 목록과 일치하지 않습니다.

-- 이와 같은 경우 역시 서로 간의 목록이 맞지 않는 관계로 에러가 날 수 밖에 없습니다.


----------------------------- 오홋~ 여기까지 p.147 ----------------------

------------------------- 대단히 수고하셨습니다 -------------------------
[이 게시물은 486i님에 의해 2008-04-17 15:59:19 예제노트 활용도100%에서 이동 됨]
[이 게시물은 486i님에 의해 2008-04-21 15:10:08 MS-SQL에서 이동 됨]