집계함수 count(집합) / sum(집합) / avg(집합) / min(집합) / max(집합)

select count(*) from sample51 where name='a'; count만 * 사용가능

select count(no), count(name) from sample51; null값은 제외하고 카운트 됨


ALL중복 상관없이 모두 조회, DISTINCT 중복제거하고 조회 기본은 ALL

select count(ALL name), count(DISTINCT name) from sample51;


select sum(quantity) from sample51; 합계

select avg(quantity), sum(quantity)/count(quantity) from sample51; 동일한 평균

select avg(case when quantity is null then 0 else quantity end) 

as avgnull0 from sample51; 널값을 0으로 변환해서 평균

select min(quantity),max(quantity),min(name),max(name) from sample51;


select * from 테이블명 group by 열1, 열2, ... 집계함수로 넘겨줄 인자를 그룹화

group by 할시 중복이 제거되어 distinct와 같은 효과

select name,count(name),sum(quantity) from sample51 group by name;

네임의 값마다 집계가 된다.

내부처리 순서 where -> group by -> having -> select-> order by

where에서는 집계함수 사용불가 대신 select에서 having으로 대체

having에서도 별명 사용불가

select name, count(name) from sample51 group by name having count(name) = 1;

name의 갯수가 1개인 모든 항목의 이름과 갯수를 검색


group by 지정한 열 이외의 열은 집계함수 사용하지 않고는 select에 포함불가

select min(no), name, sum(quantity) from sample51 group by name;


서브쿼리 : 쿼리 안에 (select)문 추가

delete from sample54 where a=(select min(a) from sample54); 

a가 가장 작은 행 삭제


서브쿼리 패턴

1. 하나의 값 반환 80 select min(a) from sample54;

2. 복수의 행, 하나의 열 select no from sample54;

3. 하나의 행, 복수의 열 select min(a),max(no) from sample54;

4. 복수의 행, 복수의 열 select no, a from sample54;


1번 패턴은 스칼라값 단일 값 스칼라 서브쿼리

스칼라 서브쿼리는 where에서 사용가능

select

    (select count(*) from sample51) as sq1,

    (select count(*) from sample54) as sq2 from dual; 

(oracle from dual 을 제외하면 mysql)

update sample54 set a=(select max(a) from sample54);

select * from (select * from samplee54) as sq; 중첩구조, 내포구조, nested구조

오라클에서는 as 제외 

오라클에서 limit 대체 명령

select * from (select * from sample54 order by a desc) sq where rownum <= 2;


insert into sample541 values

( (select count(*) from sample51), (select count(*) from sample54) );

insert into sample541 select 1,2; 동일 insert into sample541 values(1,2);

insert into sample542 select * from sample543; 테이블 복사


상관서브쿼리 

exist(select 명령) 반환 값의 존재 여부 확인

update sample551 set a='있음' where 

    exists (select * from sample552 where no2 = no);

update sample551 set a='없음' where

    not exists (select * from sample552 where no2 = no);


열에 테이블명 붙이기

update sample551 set a='있음' where

    exists (select * from sample552 where sample552.no2 = sample551.no);


열명 in 집합

select * from sample551 where no in (3,5);

select * from sample551 where no in (select no2 from sample 552);

NOT IN은 집합에 값이 포함되어있지 않으면 참 / NULL체크는 불가

블로그 이미지

dev김

안드로이드 개발자로 만 4년이 좀 안되게 근무했었고 그 이상의 공백을 가지고 있다. 다시 현업에 복귀하기 위한 노력의 흔적을 담으려고 한다.

,