[목차]

5. Query 

    1) select from

    2) where

    3) order by

6. 그룹화 (group by, having)

 

[내용]

5. Query 
    1) 기본 select 
    [형식] 
     전체데이터 조회

select * 
from 테이블명; 

 

    - SQL문은 대소문자 구분하지않음. 
    ; 문장의 종료를 의미. 여러줄로 명령입력 가능. 
    - select문에서 * 사용시 모든 칼럼표시의미 
   
    ② 원하는 칼럼만 조회

select 칼럼명1, 칼럼명2 as alias, 칼럼명3 alias 
from 테이블명 

    - 칼럼명 대신 alias 사용가능. 
       as와 함께 쓰거나 한칸 띄고 정의. 
       alias에 공백사용을 원할 경우 ""큰따옴표 사용."급여의 합계" 

select (sal*12)+comm "급여의 합계" 
select ename'짱' 
select ename||'의 급여는'||sal||'입니다'as Info 

    - select 문에서 칼럼을 연산의 결과로 정의가능.

    - 여러개의 칼럼을 연결하여 하나의 칼럼 정의가능. 
      || 연산자를 이용하여 표현가능. 

  - 칼럼의 값으로 null 저장가능. 
    null은 0이나 공백이 아닌 지정되지 않은 값. null은 연산 불가. 연산 후도 null. 
  - ''작은 따옴표는 오라클에서 문자열이나 날짜 데이터를 표현할때 사용.


  - 중복된 데이터를 제거하기 위해서 [distinct]를 select절에 추가할 수 있다. 
  


    2) select문에 조건 추가하기 (where)
    [형식]

select[distinct] 칼럼명1, 칼럼명2...[별칭] 
from 테이블명 
where 조건식1(칼럼명 연산자 적용할 값) and(or) 조건식2 

 

    - 검색결과 제한 
    - from절 다음에 정의. 
    - where절은 조건식이 true인 데이터만 조회. 
    - where절에 사용할 수 있는 비교연산자. 
      =, >, >=, <, <=, (<>, !=, ^=) 
    - where절에 날짜나 문자열 사용시 ''작은 따옴표 사용. 
    - 오라클은 1970년 부터 Date를 셈. 
    - 나머지는 1900년 부터 Date를 셈. 
    - 조건을 여러개 정의 시 where절에 and, or 연산자 함께사용.

 

    - and : 모든 조건이 모두 만족할 경우(모두 true)

select empno,ename,job,sal
from emp
where job='SALESMAN' and sal>=1500;
select deptno, ename, job, sal, hiredate, deptno
from emp
where sal>=2800 and job='MANAGER';

   - or : 조건 중 하나만 만족할 경우(하나라도 true)

select empno, ename, sal, hiredate
from emp
where hiredate>='81/1/1' or sal >=5000;

 

    - and 조건 대신 사용할 수 있는 연산자. 
      칼럼명 between A and B : A와 B 사이값 
      하나의 칼럼에 여러 조건을 적용할 경우.

select ename||':'||job as "name : job"
from emp
where hiredate between '81/1/1' and '81/12/31' and job='MANAGER';

 

select ename, job, sal, deptno
from emp
where sal between 1300 and 1700;

    - or 조건 대신 사용할 수 있는 연산자. 단, 하나의 칼럼에 여러 조건을 줄 경우. 
      칼럼명 in (값1, 값2, 값3) 
      부서가 10, 20 부서인 조회

select ename, sal, deptno
from emp
where deptno in (10,20) and sal >=2000;
select deptno, ename, job, sal, hiredate
from emp
where empno in (7902, 7788, 7566);
select deptno, ename, job, sal, deptno
from emp
where job not in ('MANAGER', 'CLERK', 'ANALYST');


    - 조건으로 정의한 값과 정확하게 일치하지 않은 조건을 적용하고 싶은 경우 like 연산자 이용하며 
      대표문자를 함께 사용해서 조회해야한다. 
      _ : 한글자 대표 
      % : 0 or 하나이상의 문자 대표

select * from emp
where ename like '%A%' 

where ename like 'A%' 

where ename like '%A' 

where ename like '_A__' 


    - null 데이터 검색하기 
      is null : null인 데이터

      is not null : null이 아닌 데이터

select ename, mgr, case when mgr is null then '상위자'
					else '담당'
					end 관리자
from emp;
select first_name, last_name, salary, commission_pct, salary+commission_pct
from employees
where commission_pct is not null
order by salary+commission_pct desc;


    - not : 조건에 대한 부정 
      not in (' ', ' ')

select department_id, avg(salary)
from employees
where department_id not in(40,50)
group by department_id
order by avg(salary) desc;


    3) 데이터 정렬 (order by)
    [형식]

select * from 테이블명 where 조건식

order by 정렬하고 싶은 칼럼 desc|asc 

 

    - desc(내림차순 정렬) : 데이터의 크기가 큰 데이터부터 출력 (10~1, ㅎ~ㄱ, Z~A, z~a)
    - asc(오름차순 정렬) : 데이터의 크기가 작은 데이터부터 출력 (1~10, ㄱ~ㅎ, A~Z, a~z)
    - 생략 시(default) 오름차순(asc)

select empno, ename, sal
from emp
where sal between 2000 and 3000
order by sal desc;

 

    - 정렬기준은 여러개로 정의 가능.

select * from 테이블명 where 조건식

order by 칼럼1 desc, 칼럼2 asc; 


  - order by절은 무조건 select문의 마지막절에 정의한다. 
  - alias 사용가능.

 

 

6. 그룹화 (group by, having)
     [구문]

select 칼럼명 그룹함수()  
칼럼의 동일한 값끼지 그룹함수를 연산한다. 
from
where
group by 칼럼명(alias사용불가) 
having 조건(그룹함수를 이용한 조건이 필요한 경우)(alias사용불가)
select deptno, count(deptno)
from emp
where sal>2000
group by deptno
having count(deptno)>=2
order by deptno;
select deptno, job, count(empno)
from emp
group by deptno, job
order by deptno;
select department_id, avg(salary)
from employees
group by department_id
having avg(salary)>=10000;

      - 테이블에 저장된 데이터를 그룹으로 나누어서 그룹별 합계, 평균, 최대값, 최소값, 레코드 개수등을 구할 수 

        있는 기능 (데이터의 집계)
      - group by절에 그룹화하고 싶은 컬럼 정의 
      - group by절을 추가하지않고 일반 칼럼명과 그룹함수를 같이 사용할 수 없다. 
      - group by를 하는 경우 select문에 group by절에 명시한 칼럼이외의 칼럼을 정의할 수 없다. 
      - where절에 그룹함수를 사용할 수 없다. 
      - where절에는 그룹화하기 전에 적용할 조건을 정의 
      - 그룹화하고 난 후 결과를 조건으로 사용하는 경우 having절을 사용 
       => 그룹함수를 써서 조건을 정의해야하는 경우는 무조건 having절에 정의. 
      - 실행순서 : from -> where -> group by -> having -> select -> order by 
      - group by 2개 이상 가능 
       => select절 칼럼순서와 group by절 순서가 일치해야함. 

+ Recent posts

1