반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*  
   PL/SQL (Procedural Language / SQL)
   :오라클에서 제공하는 프로그래밍 언어
   :일반 프로그래밍 언어적인 요소를 다 가지고 있어 데이터베이스 업무를 처리하기 위한 최적화된 언어
   
   //기본 구조
   - 선언부(Declare) : 모든 변수나 상수를 선언하는 부분
   - 실행부(Executable) : begin ~ end / 제어문, 반복문, 함수정의 등의 로직을 기술하는 부분
   - 예외처리부(Exception) : 실행도중 에러발생 시 문제를 해결하기위한 명령들을 기술하는 부분
   
   Declare, begine, exception 키워드들은 ';'을 붙이지 않는다.
   나머지 문장들은 ';'으로 처리한다
   
   //처리
   - 익명블록(Anonymous PL/SQL Block) : 주로 1회성으로 사용할 경우 많이 사용
   - 저장블록(Stored PL/SQL Block) : 서버에 저장해 놓고 주기적으로 반복해서 사용할 경우 사용
*/
set serveroutput on/* set serveroutput off;  */
 
declare
    cnt integer;
begin
    cnt := cnt+1;  /* 할당연산자 ':=' */
    if cnt is null then
        dbms_output.put_line('결과 : cnt는 null');  /* 출력문 */
    end if;
end;
/  /* 실행하라는 의미 */
 
 
declare
    empNo number(20);
    empName varchar2(10);
begin
    select employee_id, first_name into empNo, empName
    from employees
    where employee_id = 124;
    
    dbms_output.put_line(empNo || ' ' || empName);
end;
/
 
 
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] ROWTYPE 변수 및 복합변수 활용  (0) 2017.09.08
[Oracle SQL] PL/SQL 변수 선언 및 데이터 타입  (0) 2017.09.06
[Oracle SQL] 계층형 쿼리  (0) 2017.08.17
[Oracle SQL] Sequence  (0) 2017.08.16
[Oracle SQL] VIEW  (0) 2017.08.16
반응형



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* 
    계층형 쿼리 
        : 오라클에서만 제공됨
*/
 
create table bom_sphone(
    item_id number(3not null,
    parent_id number(3),
    item_name varchar2(20not null,
    primary key (item_id)
);
 
 
insert into bom_sphone values(100,null,'스마트폰');
insert into bom_sphone values(101,100,'메인pc');
insert into bom_sphone values(102,100,'배터리');
insert into bom_sphone values(103,101,'cpu');
insert into bom_sphone values(104,101,'메모리');
insert into bom_sphone values(105,101,'블루투스');
 
 
select * from bom_sphone;
 
 
 
select  s1.item_name, s1.item_id,s2.item_name parent_name
from bom_sphone s1, bom_sphone s2
where s1.parent_id = s2.item_id (+)
order by s1.item_id;
 
 
 
/* start with, connect by절을 이용한 계층형 쿼리를 할 수 있다 */
 
select lpad('*'2*(level-1)) || item_name itemnames
from bom_sphone
start with parent_id is null /* 최상위 nod지정 */
connect by prior item_id = parent_id; 
 
 
 
/* 
    prior는 부모열을 찾아주는 의미 
    = connect by parent_id = prior item_id
*/
 
select level, lpad(' '4*(level-1)) || first_name||' '||last_name "이름"
from employees
start with manager_id is null /* 부모가 없으므로 최상위가 됨 */
connect by manager_id = prior employee_id;
 
 
select job.job_title, lpad(' '4*(level-1)) || emp.first_name||' '||emp.last_name "이름"
from employees emp, jobs job
where emp.job_id = job.job_id
start with emp.manager_id is null 
connect by emp.manager_id = prior emp.employee_id;
cs








반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] PL/SQL 변수 선언 및 데이터 타입  (0) 2017.09.06
[Oracle SQL] PL/SQL  (0) 2017.08.21
[Oracle SQL] Sequence  (0) 2017.08.16
[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] 무결성 제약조건  (0) 2017.08.12
반응형





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* 
    Sequence (시퀀스) 
        : 순서
        : 연속적인 번호를 만들어 주는 기능
        : 각각의 레코드가 추가될 때마다 자동으로 줄번호가 생기는 것
        : mySQL에서 auto_increment 사용
        : 오라클에서는 시퀀스 제공
    
    구문형식
    create sequence 시퀀스 이름
       
        increment by n <- 증가값(n) 설정, 기본값은 1 
        start with n <- 시작값(n) 설정, 기본값은 1
       
        maxvalue n   <- 시퀀스 최대값(n) 설정
        nomaxvalue n  <- 맥스를 설정하지 않고 계속 증가하게 함
       
        minvalue n <- 시퀀스 최소값 : cycle옵션일 경우 시작 값
        nominvalue n <- 최소를 설정하지 않고 계속 증가하게 함
        
        cycle <- 시퀀스를 순환사용할지 설정
        nocycle
       
        cache n <- 시퀀스의 속도를 개선하기 위해 캐싱여부 지정
        no cache n
    
*/
 
/* 시퀀스 생성 : 제품번호 생성하는 시퀀스 만들기 */
 
create sequence seq_serial_no
increment by 1
start with 100
maxvalue 110
minvalue 99
cycle
cache 2;
 
 
 
create table good(
    good_no number(3),
    good_name varchar2(10)    
);
 
 
 
insert into good 
values (seq_serial_no.nextval, '제품1');
 
insert into good 
values (seq_serial_no.currval, '제품1');
 
 
 
 
/*  
   nextval : 다음 value
   currval : 현재 value
*/
 
insert into good 
values (seq_serial_no.nextval, '제품2');
 
 
select * from good;
 
 
select seq_serial_no.currval from dual;
 
 
 
/* 
    제품번호가 Maxvalue인 110까지 생성된 이후(Cycle이 끝난 후) 한번 더 생성하면
    minvalue인 99로 생성됨
 */
 
insert into good 
values (seq_serial_no.nextval, '제품12');
 
 
create table good2(
    good_no number(3),
    good_name varchar2(10)
    );
    
 
create sequence seq_serial_no2
increment by 1
start with 100
maxvalue 105
cache 2;
 
 
insert into good2
values (seq_serial_no2.nextval, '제품1');
commit;
 
 
select * from good2;
 
 
 
/* 
    데이터베이스 다운시키는 명령어
    cmd창에서 입력
    sqlplus 
    hr
    비번입력
    select * from good2;
    
    conn sys/비번 as sysdba;
    
    shutdown abort;
    데이터베이스 시작시키는 명령어
    starup
    conn hr /비번
    select * from good2;
    
    insert into good2 values(seq_serial_no2.nextval,'제품2');
    select * from good2;
    
 */
 
 
/* 시퀀스 삭제 */
drop sequence 시퀀스명;
 
 
/* 
    시퀀스 감소
    increment by 1 값에 음수를 적용 
*/
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] PL/SQL  (0) 2017.08.21
[Oracle SQL] 계층형 쿼리  (0) 2017.08.17
[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] 무결성 제약조건  (0) 2017.08.12
[Oracle SQL] INSERT, UPDATE, DELETE, COMMIT, ROLLBACK  (0) 2017.08.10
반응형







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/* 
    View (뷰) : table과 유사하며, 테이블처럼 사용한다
              : 데이터를 저장하기 위한 물리적 공간이 필요하지 않은 가상테이블
              : 데이터를 물리적으로 가지지 않지만 논리적인 집합을 가짐
              : 테이블과 마찬가지로 select, insert, update, delete 명령어가 가능하다
              : create을 사용해서 view를 생성함
              
    사용이유
        : 보안관리
            - 보안등급에 맞춰 컬럼 및 범위를 정해 조회하도록 함
            - 연산 결과만 제공하고 알고리즘을 숨기기 위해 사용
            - Selectlist를 함수로 가공하여 update, insert를 못하도록 함
            - 테이블 명이나 컬럼 명을 숨기도록 함
            
        : 사용편의성
            - 검색조건을 단순화하여 사용할 수 있도록 함
            - 조인을 단순화
            - 사용자를 위한 컬럼명이나 테이블명 제공
*/
 
/* View 생성 */
 
create view v_emp(emp_id, first_name,job_id, hiredate, dept_id) as
select employee_id, first_name, job_id, hire_date, department_id
from employees
where job_id = 'ST_CLERK';
 
 
 
select * from v_emp;
 
 
 
create view v_emp1(emp_id, first_name,job_id, hiredate, dept_id) as
select employee_id, first_name, job_id, hire_date, department_id
from employees
where job_id = 'SH_CLERK';
 
 
 
select * from v_emp1;
 
 
 
 
/* View 관리 */
 
select * from v_emp1;
 
 
 
/* View 삭제 */
 
drop view v_emp1;
 
desc v_emp1;
 
 
 
/* View 수정 */
 
create or replace view v_emp(emp_id, first_name,job_id, hiredate, dept_id) as
select employee_id, first_name, job_id, hire_date, department_id
from employees
where job_id = 'SH_CLERK';
 
select * from v_emp;
 
 
 
/* View활용 */
/* 
    보안 
    nvl (컬럼명,null) - 데이터를 수정할 수 없도록 함
*/
create view v_emp3(emp_id, first_name,job_id, hiredate, dept_id) as
select employee_id , nvl(first_name, null), job_id, hire_date, department_id
from employees
where job_id = 'SH_CLERK';
 
 
select * from v_emp3;
 
 
 
/* 에러발생 */
 
update v_emp3 set first_name = 'kim'
where first_name = 'Julia'
 
select * from v_emp3;
 
 
 
update v_emp set first_name = 'kim'
where first_name = 'Julia'
 
select * from v_emp;
 
 
 
 
/* 연산과정 숨기는 방법 */
 
create view v_emp_salary(emp_id, last_name, annual_sal) as
select employee_id, last_name, (salary+nvl(commission_pct,0)) * 12
from employees;
 
 
select * from v_emp_salary;
 
 
 
 
/* read only : 데이터 수정 불가 */
 
create view v_emp_readonly(emp_id, last_name, annual_sal) as
select employee_id, last_name, (salary+nvl(commission_pct,0)) * 12
from employees
with read only;
 
 
select * from v_emp_readonly;
desc v_emp_readonly;
 
 
 
 
/* 읽기전용이므로 수정 불가  */
 
update v_emp_readonly
set last_name ='kim'
where last_name='Grant';
 
 
 
/* 사용자 편의성 */
 
create view v_samp1 as
select employee_id, last_name, department_id, hire_date
from employees
where (salary+nvl(commission_pct,0))*12 > 30000
  and department_id = 50
  and job_id = 'ST_CLERK'
  and sysdate - 365 * 5> hire_date ;
 
 
 
select * from v_samp1;
 
 
 
create view 사원 (사번, 이름, 부서번호, 입사일) as
select employee_id, first_name ||' '||last_name, department_id, hire_date 
from employees
where department_id = 50;
 
 
select * from 사원;
 
 
 
/* Join table View */
 
create view v_join(사번, 이름, 부서번호, 부서명, 입사일) as
select emp.employee_id, emp. first_name ||' '||last_name, emp.department_id, 
       dept.department_name, emp.hire_date
from employees emp, departments dept
where emp.DEPARTMENT_ID = dept.DEPARTMENT_ID;
 
select * from v_join;
cs


반응형
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/* 
    제약조건 : 데이터 저장 시 저장가능한 조건이 존
    무결성 제약조건 = 컬럼 속성
    NOT NULL : 널값이 입력되지 못하게하는 조건
    UNIQUE : 중복된 값이 입력되지 못하게하는 조건 (NULL값 허용가능)
    PRIMARY KEY : NOT NULL + UNIQUE의 의미
                : 데이터 식별 시 유일성을 가짐
    FOREIGN KEY (외래키) : 다른테이블 칼럼 참조해서 무결성을 검사하는 조건
    CHECK : 주어진값만 허용하는 조건
*/
/* NULL : 데이터가 없음을 의미 */
 
create table null_test(
    col1 varchar2(20not null,
    col2 varchar2(20null,
    col3 varchar2(20
    );
 
 
desc null_test;
 
 
insert into null_test (col1,col2)
values ('aaa','bb');
 
 
select * from null_test;
 
 
/* col1이 not null이므로 에러발생 */
 
insert into null_test (col2,col3)
values ('cc','dd');
 
 
 
/* Unique  */
 
create table unique_test(
    col1 varchar2(20unique not null,
    col2 varchar2(20unique,
    col3 varchar2(20not null,
    col4 varchar2(20not null,
    constraints temp_unique unique(col3,col4)
    );
 
 
 
/* 
    constraints : 강제로 제약을하겠다는 의미
                : col3과 col4을 조합한 값을 unique로 사용하겠다는 의미
                : temp_unique는 unique의 이름
*/
 
 
insert into unique_test (col1,col2,col3,col4)
values ('aa','bb','cc','dd');
 
 
insert into unique_test (col1,col2,col3,col4)
values ('a2','b2','c2','d2');
 
 
select * from unique_test;
 
 
/* 무결성제약조건 위배 : col1의 값은 unique해야하는데 이미 aa가 존재하므로 에러 */
 
update unique_test
set col1 = 'aa'
where col2 = 'b2';
 
 
 
/* Unique는 null을 허용하므로 에러없음 */
 
insert into unique_test (col1,col2,col3,col4)
values ('a3','','c3','d3');
 
 
insert into unique_test( col1,col2,col3,col4)
values ('a4','','c4','d4');
 
 
 
/* Primary Key : 기본키 (null허용하지 않음) */
/* 테이블 생성 시 기본 키 생성방법 */
 
create table primary_test(
    student_id number(10primary key/* 인라인 방식 */
    name varchar2(20)
);
 
 
create table primary_test(
    student_id number(10), 
    name varchar2(20),
    constraints student_pk primary key(student_id) /* 아웃라인 방식 */
);
 
 
/*  
    인라인, 아웃라인 차이
    primary key의 이름을 명시하느냐 오라클에서 자동으로 생성하느냐의 차이
*/
 
desc primary_test;
 
 
/* 테이블 생성 후 기본키 생성방법 */
 
alter table primary_test
add constraints "기본키 이름" primary key(필드명);
 
 
 
/* 
    FOREIGN KEY : 외래키
                : 부모테이블이 존재해야 자식테이블에서 외래키 사용 가능
 */
 
create table foreign_key(
    department_id constraints dept_fk 
    references departments (department_id) /* 인라인 */
    );
 
 
create table foreign_key(
    department_id
    constraints dept_fk 
    foreign key (department_id)
    references departments(department_id) /* 아웃라인 */
    );
 
 
 
/* 테이블을 생성하고 나서 외래키를 지정하는 방법 */
 
alter table foreign_key
add constraints dept_fk foreign key (department_id)
references departments(department_id);
 
 
 
/* 자식테이블에서 사용하지 않은 값은 부모테이블에서 삭제 가능 */
/* Check : 입력값을 체크해서 조건에 해당하지 않으면 입력불가 */
 
create table check_test(
    gender varchar2(10not null
    constraints check_sex check(gender in('M','F'))
    );
 
 
create table check_test(
    gender varchar2(10not null
    constraints check_sex check(gender in('남성','여성'))
    );
 
 
 
/* 체크 제약조건에 위배되므로 에러 */
 
insert into check_test
values('남자');
 
 
insert into check_test
values('여성');
 
 
select * from check_test;
cs



반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] Sequence  (0) 2017.08.16
[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] INSERT, UPDATE, DELETE, COMMIT, ROLLBACK  (0) 2017.08.10
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* 
    DML (Data Manipulation Language) : 데이터 조작어
    SELECT문, DELETE문, INSERT문, UPDATE문
    
    --형식--
    SELECT 컬럼명, 컬럼명2,...
    FROM 테이블1, 테이블2,...
    WHERE 조건들
    
    //테이블의 레코드(로우)를 입력
    INSERT INTO 테이블명 (컬럼명1, 컬럼명2, ...)
    VALUES (값1, 값2, ...); 
    
    UPDATE 테이블명 
    SET 컬럼명1 = 값1,
        컬럼명2 = 값2
    WHERE 조건..;
    
    
    //테이블의 레코드(로우)를 삭제
    DELETE (FROM-생략가능)테이블명
    WHERE 조건;   
*/
    
/* 테이블 생성 */
 
create table sample(
    deptNo number(20),
    deptName varchar2(15),
    deploc varchar2(15),
    depManager varchar2(10)
);
 
 
desc sample;
 
 
 
/* 데이터 입력 */
 
insert into sample(deptNo, deptName, deploc, depManager)
values(10'기획실''서울''홍길동');
 
 
select * from sample;
 
 
 
/* 모든 컬럼에 데이터를 넣을 경우 컬럼명 생략가능 */
 
insert into sample
values(20,'전산실','부산','김말동');
 
 
insert into sample
values(30,'영업부','광주',null);
 
 
 
/* 데이터 필드 수정 */
 
update sample set deptNo=50
where deptNo=30;
 
 
update sample set deploc = '인천'
where deptNo = 50;
 
 
 
/* 데이터 삭제 */
 
delete sample 
where deptNo = 50;
 
 
 
/* 테이블 내용 모두 삭제 */
 
delete sample;
 
 
 
/* commit  */
 
insert into sample
values(20,'전산실','부산','김말동');
 
 
insert into sample
values(30,'영업부','광주',null);
 
 
commit;
 
 
 
/* rollback : commit한 시점으로 돌아감*/
 
update sample set deploc = '인천'
where deptNo = 30;
 
 
select * from sample;
 
 
delete sample;
 
 
rollback;
 
select * from sample;
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] VIEW  (0) 2017.08.16
[Oracle SQL] 무결성 제약조건  (0) 2017.08.12
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] SubQuery 서브쿼리  (0) 2017.08.10
[Oracle SQL] Join  (0) 2017.08.08
반응형






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*  DDL (Data Definition Language) : Creat문, Drop문, Alter문, Truncate문 */
 
/* Create Table */
 
 create table employees2(
    employee_id number(10),
    name varchar2(20),
    salary number(7,2)
 );
 
 
select * from employees2;
 
 
 
/* 같은 테이블을 동일하게 만들 때 */
 
create table employees3 
as
select * from employees2;
 
 
select * from employees3;
 
 
 
/* Alter - add: 테이블 추가 */
 
alter table employees2 add(
    manager_id varchar2(10)
    );
 
 
select * from employees2;
 
 
 
/* Alter - modify : 테이블 수정 */
 
alter table employees2 modify(
    manager_id varchar2(20)
    );
 
 
 
 
/* Alter - drop column : 칼럼 삭제 */
 
alter table employees2 drop column manager_id;
 
 
select * from employees2;
 
 
 
/* 
    문자형 데이터 
    char, varchar, nchar, nvarchar, long 형태 존재
    long은 최대 2GB가능 
 */
 
/* Drop문 : 테이블 구조를 삭제 */
 
drop table employees2;
 
 
select * from employees2;
 
 
/* Rename */
 
Rename employees3 to employees2;
 
 
desc employees3;
desc employees2;
 
/* Truncate : 테이블 내의 모든 레코드 삭제 */
 
truncate table employees2;
 
 
select * from employees2;
cs


반응형
반응형





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
 서브쿼리 
    : Main Query에 반대되는 개념
    : 메인쿼리를 구성하는 소단위 쿼리
    : select / insert / delete / update 절에서 모두 사용가능
    : 서브쿼리의 결과 집합을 메인 쿼리가 중간 결과값으로 사용
    : 서브쿼리 자체는 일반 쿼리와 다를 바 없음
 */
 
 select round(avg(salary)) 
 from employees;
 
 
 select employee_id, first_name, last_name
 from employees
 where salary < 6462;
 
 
 /* Where절에서는 집계함수 사용 불가 */
 
 select employee_id, first_name, last_name
 from employees
 where salary < round(avg(salary));
 
 
 
 /* select서브쿼리 문 */
 
 select employee_id, first_name, last_name
 from employees
 where salary < (select round(avg(salary)) 
                 from employees);
 
 
 
 select location_id
 from locations
 where state_province is null;
 
 
 
 select * from departments
 where location_id in ( select location_id
                       from locations
                       where country_id = 'US' );
 
 
 
/* 월급이 가장 적은 사원 */
 
select emp.first_name, emp.last_name, job.job_title, emp.salary
from employees emp, jobs job
where emp.salary = (select min(salary) from employees)
  and emp.job_id = job.job_id;
 
 
 
/* 월급이 가장 많은 사원 */
 
select emp.first_name, emp.last_name, job.job_title, emp.salary
from employees emp, jobs job
where emp.salary = ( select max(salary) from employees)
  and emp.job_id = job.job_id;
  
 
 
/* 평균 급여보다 많이 받는 사원들의 명단 조회 */
 
select emp.first_name, emp.last_name, job.job_title
from employees emp, jobs job
where emp.salary > (select avg(salary) from employees)
  and emp.job_id = job.job_id;
 
 
 
/* any, all */
 
select salary
from employees
where department_id = 20;
 
 
 
/* department_id = 20의 최소 연봉보다 많이 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary > any ( select salary
                     from employees
                     where department_id = 20 );
 
 
 
select employee_id, department_id, salary
from employees 
where salary > ( select min(salary)
                 from employees
                 where department_id = 20 );
 
 
 
/* department_id = 20의 최대 연봉보다 많이 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary > all ( select salary
                     from employees
                     where department_id = 20 );
 
 
 
select employee_id, department_id, salary
from employees 
where salary > ( select max(salary)
                 from employees
                 where department_id = 20 );
 
 
 
/* department_id = 20의 연봉과 동일하게 받는 사람 모두 출력 */
 
select employee_id, department_id, salary
from employees 
where salary in ( select salary
                 from employees
                 where department_id = 20 );
cs


반응형

'프로그래밍 > SQL' 카테고리의 다른 글

[Oracle SQL] INSERT, UPDATE, DELETE, COMMIT, ROLLBACK  (0) 2017.08.10
[Oracle SQL] CREATE, ALTER, DROP, TRUNCATE  (0) 2017.08.10
[Oracle SQL] Join  (0) 2017.08.08
[Oracle SQL] GROUP BY, HAVING, ROLLUP  (0) 2017.08.08
[Oracle SQL] 날짜함수  (0) 2017.08.06

+ Recent posts