1005 데이터베이스 정리
* SQL 데이터베이스에 저장된 데이터를 불러오는 명령어
- select 컬럼
- from 테이름 이름
- where 필터링
* 오늘 수업 내용
그룹핑, 정렬, 그룹핑 필터링
1. 정렬(order by) : 특정 필드를 기준으로 정렬화
- 사용형식 : select 컬럼 from 테이블 이름 where 조건 order by 특정필드
- desc 내림차순, asc 오름차순
- order by에 default 정렬은 오름차순
- 실행순서 from => where => select => order by
ex)
- select ename, sal from emp order by 2
( 위에서 2는 enama=1, sal=2 를 가져와서 sal을 뜻함)
- 사원들의 사원 이름, 입사날짜 조회 (단, 입사날짜를 내림차순 하시오.)
select ename, hiredate from emp order by hiredate desc
2. 함수를 이용해서 특정내용 찾기
1) like 함수
: like를 사용하면 특정문자를 포함한 컬럼을 찾을 수 있다.
ex)
- like 이용해서 이름에 a가 한번이라도 들어간 사원 찾기
select ename from emp where ename like "%a%"
- 성이 a로 시작하는 사원 검색
select ename from emp where ename like "a%"
- 성이 a로 끝나는 사원 검색
select ename from emp where ename like "%a"
2) is함수
- is null : 값이 null인 컬럼 조회할 때 사용
ex)
select comm from emp where comm is null
- is not null : null이 아닌 컬럼 조회
ex)
select comm from emp where comm is not null
- ifnull : null인 컬럼을 임시로 다른 데이터로 채워줌.
ex)
select ifnull(comm,50) from emp <- comm에 null이 있으면 50을 값으로 준다.
2. 그룹핑 (group by ): 특정 필드를 기준으로 그룹화
ex)
select job from emp group by job
- sum, max, min, avg, count와 사용 가능
ex)
select job, count(*) from emp group by job
- 부서번호별로 그룹핑 조회(가장 높은 급여 포함)
select deptno, max(sal) from emp group by deptno
- 부서번호로 그룹핑하고 부서별 평균 급여 조회
select deptno, avg(sal) from emp group by deptno order by avg(sal)
* 단, 주민등록번호, 사원번호 같은 고유번호를 기준으로는 그룹화 불가능
3. gruop by 필터링(having)
: where 조건에는 sum, avg, max... 같은 함수를 사용할 수 없다
= > where 대신 having을 사용
ex)
select job, sum(sal) from emp group by job having sum(sal)>=5000
select job, avg(sal) from emp group by JOB having sum(sal)>=5000
-> having은 group by 뒤에 온다.
* 작동 순서
: from => where => group by => having => select => order by
ex)
select job, avg(sal) from emp
where job = 'manager'
group by JOB having avg(sal) >= 2000
order by avg(sal) desc
댓글
댓글 쓰기