*
- create table 컬럼명 as
- 가상 테이블, 읽기 전용, 반복(자주)되는 작업 시
- 주의 : view에서는 별칭이 정식명칭이다
- 조인 구문의 결과를 저장 할 때
* 인라인 뷰
- 임시(일회성) 객체
* 행번호
- 결과셋에서 특정 갯수만큼의 레코드를 가져오거나 특정 위치의 레코드를 가져오는 행을 한다. ***


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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
 
-- 1. 어떤 비디오 있나?
select * from tblVideo;
 
-- 2. 어떤 비디오(tblVideo) & 대여가격 & 기간(tblGenre)?  ->join
select v.name, g.price from tblGenre g 
  inner join tblVideo v 
      on g.name = v.genre;
 
-- 3. 어떤 회원? 어떤 비디오? 언제빌림? 
--  : 3개 테이블 join, 순서 : 회->대->비(선 명시)
 
--회ㅁ    비ㅁ - 장ㅁ
--   \대ㅁ/
 
select * from tblRent;
 
select m.name as mname, v.name as vname, r.rentdate 
 from tblMember m
    inner join tblRent r
        on m.pk = r.who  -- pk = fk
            inner join tblVideo v
                on v.pk = r.what;
    
-- 4. 어떤 회원? 어떤 비디오? 언제? 대여가격? 
--  : 4개 테이블  join, 순서 : 장->비->대->회
 
select m.name as "회원명", v.name as "제목", r.rentDate as "대여일", g.price as "대여가격" 
  from tblGenre g
    inner join tblVideo v
        on g.name = v.genre --1번 선
 
            inner join tblRent r
                on v.pk = r.what --2번 선
 
                  inner join tblMember m
                      on r.pk = m.who; --3번 선
           
           
           
                      
                      
                      
                      
-- View, 뷰     
--  : 테이블과 유사한 객체
--  : 데이터를 가지고 있고, 주로 select 작업의 대상이 된다.
--  : 뷰테이블, 가상테이블
--  : 뷰는 select 작업에만 사용(insert, update, delete 사용 불가) -> 읽기 전용
--  : 뷰는 select 결과의 데이터를 저장(x) -> select문 자체 저장(o)
 
 
-- 1. 뷰 생성 : 기존 테이블을 복사
create view vwInsa
as
  select * from insa;
  
-- 2. 뷰 사용
select * from vwInsa;
 
 
-- 용도?
-- 담당 업무 -> insa -> 직원명, 사는곳, 급여 출력
select name, city, basicpay from insa;
 
create view myInsa
as
  select name, city, basicpay from insa;
 
select * from myInsa; --간편.,**
 
-- 인사 테이블(남/녀)?
-- 남자 사원 테이블
-- 여자 사원 테이블
create table mInsa
as
  select * from insa where substr(ssn, 81= '1';
 
create table fInsa
as
  select * from insa where substr(ssn, 81= '1';
 
select * from mInsa;
select * from fInsa;
 
 
-- 영업부 직원
create table 영업부직원
as
  select * from insa where buseo = '영업부';
  
select * from 영업부직원;
 
 
-- 주의사항
create view vwInsa3
as
  select name as "직원명"'19' || substr(ssn, 12) as birthYear from insa;
 
select * from vwInsa3; --view에서는 별칭 정식명칭
 
 
-- 뷰 사용 -> 조인 구문의 결과를 저장 할 떄 유용
-- 비디오 누가? 뭐? 언제?
create view vwRent
as
select m.name as mname, v.name as vname, r.rentDate from tblMember m
    inner join tblRent r
        on m.pk = r.who
            inner join tblVideo v
                on v.pk = what;
 
select * from vwRent;
 
--
create view tblAS
as
  select * from tblCountry where cont ='AS';
-- 뷰가 테이블의 복사본
select * from tblAS; 
-- 원본 수정
update tblCountry set popu = popu + 1000 where name = '대한민국'-- 주의 : 원본데이터 수정하면 뷰테이블도 수정됨(실시간처리)
 
 
 
 
-- 행번호
--  : 의사 컬럼, Pseudo Column
--  : 행의 일련 번호를 반환
--  : 결과셋의 레코드의 순서를 가져오는 컬럼
--  : *** 결과셋에서 특정 갯수만큼의 레코드를 가져오거나 특정 위치의 레코드를 가져오는 행을 한다.
--  : order by 영향을 받지 않는다. -> order by를 하기 이전의 상태를 가지고 행번호를 매긴다.
 
select name, rownum from tblCountry;
select name, popu, rownum from tblCountry order by popu asc;
 
select name, rownum from tblCountry where rownum = 1;
select name, rownum from tblCountry where rownum between 1 and 3;
 
 
-- 인라인 뷰, Inline View
--  : 서브쿼리의 일종
--  : 문법은 서브쿼리의 일종이고, 역할은 뷰 역할을 한다.
--  : 영구 객체x -> 임시 객체o
 
-- 뷰 : 영구 객체, 자주 사용하는 select는 뷰로 생성
-- 인라인뷰 : 임시 객체, 1회성 뷰 역할
create view vwMember 
as
  select * from tblMember where bYear >= 1980;
  
select * from vwMember;
 
select * from select * from tblMember where bYear >= 1980;; --**
 
 
-- 인구수가 가장 많은 나라 1~3위?
select name, popu, rownum from tblCountry;
select name, popu, rownum from tblCountry order by popu desc;
 
select a.*, rownum from
(select * 
    from (select name, popu 
        from tblCountry 
            where popu is not null 
                order by popu desc) --테이블1개
                      where rownum <= 3) a; --**
 
 
-- 게시판 -> 페이징 -> rownum
select * from insa;
-- 이름순으로., 페이징
--  -> 순서 : 원하는 정렬상태로 만들기(order by) -> 테이블로 취급(괄호) -> 넘버링
select name, city, buseo, rownum 
    from (select * from insa order by name asc)
        where rownum between 1 and 10;
 
select a,*, a.rnum from
(select name, city, buseo, rownum 
    from (select * from insa order by name asc)
        where a.rnum >= 11 and a.rnum <= 20;
        
        
        
-- 테이블 명령
--  : alter 명령
 
-- 테이블 수정
-- 1. 테이블 수정(alter)
-- 2. 테이블 삭제(drop) -> 테이블 생성(create) -> 데이터 추가(insert)
 
-- 테이블 수정작업?
--  1. 새로운 컬럼 추가
--  2. 기존 컬럼 삭제
--  3. 기존 컬럼 수정
 
create table tblEdit
(
  seq number not null,
  data varchar2(10not null
);
 
desc table tblEdit;
 
-- ex]새 컬럼 추가
alter table tblEdit
  add (data2 varchar2(10not null);
 
insert into tblEdit values (1'홍길동''아무게');
select * from tblEdit; --확인
 
-- 새 컬럼 추가(not null > ??)
alter table tblEdit
  add (data3 varchar2(10not null); --x, not null
  
alter table tblEdit
  add (data3 varchar2(10default '임시' not null);  --o, default 넣어주면 ok
 
alter table tblEdit
  add (data4 varchar2(10default '임시' not null);
 
 
 
-- ex] 컬럼명 수정하기
-- data3 -> data5
alter table tblEdit
    rename column data3 to data5;
 
select * from tblEdit;
 
-- 컬럼 구조 수정하기(길이, not null)
alter table tblEdit
    modify (data4 varchar2(20));
 
 
-- 제약사랑(관계) : PK - FK
create table tblParent
(
  seq number not null--기본키
  data varchar2(10not null
);
 
alter table tblParent
  add constraint tblParent_seq_pk primary key (seq); --제약사항
  
insert into tblParent values (1'홍길동');
insert into tblParent values (2'아무게');
insert into tblParent values (1'하하하'); --에러] unique constraint
 
 
create table tblChild
(
  seq number primary key--기본키
  data varchar2(10not null,
  pSeq number not null --참조키(PK) : tblParent(seq)
);
 
alter table tblChild
  add constraint tblChild_pSeq_fk 
    foreign key (Seq) references tblParent(seq); --FK
 
insert into tblChild values (1'하하하'1);
insert into tblChild values (2'호호호'5);
 
 
select * from tblParent;
select * from tblChild;        
        
 
-- ex] 컬럼 삭제
desc table tblEdit;
alter table tblEdit
    drop (data5); --**
        
select * from tblEdit;
 
 
cs


* 테이블간의 관계
- 무결성 유지

* 참조키(foreign ky, FK)
- 반드시 참조하는 컬럼에 이미 존재하는 값 중에 하나를 삽입**
- FK는 PK를 참조
- 참조시 관계를 맺는 기준? -> 나중에 생기는 테이블(FK)이 먼저 생기는 테이블(PK)을 참조****
* Join (옆으로 합)
- 내부조인 : 쓸모있는 데이터만 남겨두는., *****연습
- 외부조인 *****
- 셀프조인, 크로스조인
- 조인 vs 서브쿼리 : 결과테이블이 같은 테이블에서 나오는지? 다른 테이블에서 나오는지?를 생각.,
* union (아래로 합)


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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
 
-- 테이블간의 관계(엔티티간의 관계)
 
-- ex1] 직원/프로젝트
 
 
-- 1. 담당 직원 테이블 생성
create table tblStaff
(
  name nvarchar2(10primary key--직원명(PK, 생략x, 중복x)
  salery number not null--월급
  address varchar2(100not null --주소
);
 
insert into tblStaff (name, salery, address) values ('홍길동'200'서울시');
insert into tblStaff (name, salery, address) values ('아무게'150'인천시');
insert into tblStaff (name, salery, address) values ('하하하'100'부산시');
 
 
select * from tblStaff;
 
 
 
-- 2. 프로젝트 테이블 생성
create table tblProject
(
  pID number primary key--프로젝트 ID(일련번호, PK)
  pName nvarchar2(100not null--프로젝트명
  --staff nvarchar2(10) not null --******중요!(재직중인 직원의 이름을 대입), 담당 직원명
  
  -- 참조키(foreign Key(FK), 외래키)
  --  : 절대로 아무 데이터나 집어넣으면 안됨!
  --  : 반드시 참조하는 컬럼에 이미 존재하는 값 중에 하나를 삽입(*********)
  --  1. 다른 테이블의 특정 컬럼을 참조
  --  2. 다른 테이블의 기본키(PK) 참조
  --  3. FK는 PK를 참조
  --  4. FK의 자료형은 PK의 자료형과 동일하게 선언(데이터가 동일하기 때문에.,)
  staff nvarchar2(10not null references tblStaff(name) 
);
 
insert into tblProject (pID, pName, staff) values (1'홍콩수출건''홍길동');
insert into tblProject (pID, pName, staff) values (2'TV광고건''아무게');
insert into tblProject (pID, pName, staff) values (3'매출분석건''아무게');
insert into tblProject (pID, pName, staff) values (4'대리점분양건''홍길동');
insert into tblProject (pID, pName, staff) values (5'노조협상건''하하하');
 
select * from tblProject;
 
 
 
-- 3. 상황설정
--  1. 문제 case1] 신입 사원 입사 -> 신규 프로젝트 할당 : 직원과 프로젝트에 추가 삽입
--    a. 신입 사원 추가(tblStaff -> insert)
insert into tblStaff values ('호호호'170'서울시'); --0
 
--    b. 신규 프로젝트 추가(tblProject -> insert)
insert into tblProject values (6'원자재매입건''호호호');
--    b. 신규 프로젝트 추가
--      물리적인 insert 작업은 성공했지만., 업무상(논리적)으로 문제 발생 -> 시스템적으로 발견 불가**
insert into tblProject values (7'고객상담건''헤헤헤');
 
 
--  2. 문제 case2] 홍길동 퇴사
delete from tblStaff where name = '홍길동'--o, 업무상 불가능
 
-- 정상적인 퇴사 절차
--    a. 프로젝트 인수인계(위임) -> 담당자명 수정(update)
update tblProject set staff = '아무게' where staff = '홍길동';
--    b. 홍길동 퇴사
delete from tblStaff where name = '홍길동'--o, 업무상 가능
 
 
 
-- 무결성 유지 : 유요한 데이터로만 시스템 유지
--    -> 데이터서버(오라클)가 내부적으로 관리
drop table tblStaff;
drop table tblProject;
 
 
-- 참조(제약사항) 후 테이블 새로 생성
--생성(staff->project)참조 당하는 것부터 -> 삭제(project->staff)
 
 
 
 
 
 
-- ex2] 고객 & 판매(매출)
-- ******참조시 기준
--  : 나중에 생기는 테이블(FK)이 먼저 생기는 테이블(PK)을 참조
 
create table tblCustomer
(
  name varchar2(10primary key--고객명(PK)
  tel varchar2(15not null--연락처
  address varchar2(100not null --주소
  --orderNo number not null references tblSales(orderNo) 불안정한 참조
);
 
create table tblSales
(
  orderNo number primary key--주문번호
  item varchar2(50not null--상품명
  num number not null--판매수량
  regDate date default sysdate not null--판매시간
  
  --참조키
  customer varchar2(10not null references tblCustomer(name) --고객명(PK), 안정적인 참조
);
 
create sequence salesSeq;
 
insert into tblCustomer values ('홍길동''010-222-3333''서울시');
insert into tblCustomer values ('아무게''010-333-4444''부산시');
insert into tblCustomer values ('하하하''010-555-6666''인천시');
 
insert into tblSales values (salesSeq.nextVal, '전화기'1default'홍길동');
insert into tblSales values (salesSeq.nextVal, '다이어리'1default'홍길동');
insert into tblSales values (salesSeq.nextVal, '노트'3default'아무게');
insert into tblSales values (salesSeq.nextVal, '볼펜'5default'아무게');
insert into tblSales values (salesSeq.nextVal, '전지우개'2default'아무게');
insert into tblSales values (salesSeq.nextVal, '마우스'1default'아무게');
insert into tblSales values (salesSeq.nextVal, '키보드'1default'하하하');
 
--비회원 구매 불가능
insert into tblSales values (salesSeq.nextVal, '키보드'1default'크크크');
 
-- 회원 탈퇴
--x, 판매내역이 남아있기 때문.,
delete from tblCustomer where name = '홍길동';
 
 
select * from tblCustomer;
select * from tblSales; --확인
 
 
 
 
 
 
 
-- ex3] 비디오 대여점
--  : 회원, 비디오(상품), 장르, 대여(장부)
 
-- 1. 장르
create table tblGenre
(
  name varchar2(10primary key--장르명(PK)
  price number not null--대여가격
  period number not null --대여기간
);
 
-- 2. 비디오
create table tblVideo
(
  pk number primary key--비디오 번호(PK)
  name varchar2(50not null--제목
  num number not null--보유수량
  company varchar2(50null--제작사
  director varchar2(20null--감독
  major varchar2(20)  null--주연배우
 
  Genre varchar2(10not null references tblGenre(name) --장르 PK 참조 --> FK 
);
 
-- 3. 회원
create table tblMember
(
  pk number primary key--회원번호(PK)
  name varchar2(10not null--이름
  grade number(1not null--회원등급(1=준, 2=정, 3=우수.,)
  bYear number(4not null--생년(성인인증)
  tel varchar2(15not null,--연락처
  address varchar2(100null--주소
  money number not null --예치금
);
 
-- 4. 대여
create table tblRent
(
  pk number primary key--대여번호(PK)
  
  who number not null references tblMember(pk), --회원번호, 대여회원 참조 
  what number not null references tblVideo(pk), --비디오번호 참조--> FK
  
  rentDate date default sysdate not null--대여시간
  retDate date null--반남시간
  remark varchar2(100null
);
 
-- 시퀀스
create sequence tblMember_seq;
create sequence tblVideo_seq;
create sequence tblRent_seq;
 
 
 
-- 조인, Join
--  : 2개 이상의 테이블 내용을 한꺼번에 가져오는 기술
--  : 관계를 맺고 있는 테이블끼리.,
 
 
--  1. 내부조인(inner join) : *****
--   : 각 테이블에 조건으로 들어간 컬럼값(무보테이블(PK) -자식테이블(FK)을 비교해서 
--     양쪽 모두 만족하는 행(PK와 FK가 동일한 값을 가지는)을 조합해서 결과셋으로 반환 
--   : 단순 조인의 결과에서 의미있는 행만 추출 -> 내부조인
--   : on -> 조인에서의 where절 역할
 
-- select 컬럼리스트 from 테이블A inner join 테이블B on 테이블A.컬럼 = 테이블B.컬럼;
 
--  2. 외부조인(outer join) : *****
--   : 내부조인 + a
 
--  3. 셀프조인(self join) : **
--   : 1개의 테이블을 가지고 조인
 
--  4. 크로스조인(corss join) 단순조인 : X
 
 
 
 
-- 조인 vs 서브쿼리
--  1. 서브쿼리
--   : 결과셋이 1개의 테이블에서 나온다. (나머지 테이블은 중간 과정에서 사용되지만 최종 출력 제외)
--  2. 조인
--   : 결과셋이 1개 이상의 테이블에서 나온다.
 
select * from insa;
select name from insa where basicpay = (select max(basicpay) from insa);
 
select * from employees;
select * from jobs;
 
--최고 급여?
select max(max_salary) from jobs;
--최고급여 받는 직책?
select * from jobs where max_salary = (select max(max_salary) from jobs);
--최대급여 받는 직원의 이름?
select * from employees 
    where job_id = (select job_id from jobs where max_salary = (select max(max_salary) from jobs));
 
 
 
 
 
-- --ex1] 크로스조인(corss join) 단순조인
select * from tblCustomer, tblSales;
 
 
 
-- --ex2] 내부조인(inner join)
select * from tblcustomer, tblSales;
 
-- ANSI SQL**
select * from tblCustomer
  inner join tblSales
      on tblCustomer.name = tblSales.customer; --PK=FK, 두컬럼이 같은 것만 가져오겠다!
-- Oracle전용
select * from tblCustomer, tblSales
  where tblCustomer.name = tblSales.customer;
 
-- 언제 사용?
-- 노트를 사간(tblSales) 회원의 전화번호(tblCustomer)? -> 전화번호
--  1. 서브쿼리
--  2. 조인
select * from tblCustomer;
select * from tblSales;
 
select tel from tblCustomer where name = (select customer from tblSales where item = '노트'); --서브쿼리
 
select tblCustomer.tel from tblCustomer
    inner join tblSales
        on tblCustomer.name = tblSales.customer
          where tblSales.item = '노트'--조인, 조인에는 항상 테이블명을 명시
 
          
-- 노트를 사간 사람의 전화번호(tblCustomer)와 몇권(tblSales)을 사갔는지? -> 두 테이블의 정보를 한 테이블에 가져오기
select * from tblCustomer where name = (select customer from tblSales where item = '노트'); --서브쿼리, x 
 
select tblCustomer.tel, tblSales.num from tblCustomer
    inner join tblSales
        on tblCustomer.name = tblSales.customer
          where tblSales.item = '노트'--조인, 서로 다른 테이블에 있는 정보를 한테이블에
 
 
-- 부산시에 사는 직원이 어떤 프로젝트를 담당했는지 프로젝트명을 출력하시오.
select * from tblStaff where address = '부산시';
select * from tblProject where staff = '하하하';
 
select pName from tblProject 
  where staff = (select name from tblStaff where address = '부산시'); --서브쿼리
 
--회사의 직원 명단과 함께 프로젝트 정보도 같이 출력하시오.
select * from tblProject
    inner join tblStaff
        on tblProject.staff = tblStaff.name; -- 조인, FK <-> PK
--최종**
select tblProject.pName from tblProject
    inner join tblStaff
        on tblProject.staff = tblStaff.name
          where address = '부산시';
 
-- 부산시(tblStaff)에 사는 직원이 어떤 프로젝트를 담당했는지
--      프로젝트명(tblProject)과 담당자의 월급(tblStaff)
select tblProject.pName, tblStaff.salery from tblProject
    inner join tblStaff
        on tblProject.staff = tblStaff.name
          where address = '부산시';
 
--
select * from tblSales;
select * from regions;
 
select * from tblSales, regions; --크로스 조인
 
select * from tblSales
    inner join regions
        on tblSales.orderNo = regions.region_id; --조인 
 
 
--별칭, Alias
select p.pName, s.salery from tblProject p
    inner join tblStaff s
        on p.staff = s.name
          where s.address = '부산시';
 
 
 
 
 
-- --ex3] 외부조인(outer join)
select * from tblCustomer; --3명(구매이력o) -> 신규 회원 추가 -> 4명(구매이력o 3명, 구매이력x 1명)
select * from tblSales; --7건 판매이력
 
insert into tblCustomer values ('호호호''010-666-7777''서울시');
 
-- 내부조인의 특징
-- 판매이력 1건 이상인 회원 정보와 판매내역을 출력하시오.
--  : 양쪽 테이블에 모두 동시에 존재하는 내용만을 가져오기
-- *** 구매이력없는 회원 정보는 제외
select * from tblCustomer c
    inner join tblSales s
        on c.name = s.customer; --이너조인(추가한 호호호가 보이지 않음)
 
-- 외부조인
-- 판매이력 1건 이상인 회원 정보와 판매내역을 출력하시오. + 구매이력이 1건도 없는 회원 정보도 같이 출력하시오.
 
-- ANSI SQL
select * from tblCustomer c
    left outer join tblSales s
        on c.name = s.customer;
-- Oracel
select * from tblCustomer c, tblSales s
    where c.name = s.customer(+);
 
 
 
 
 
-- --ex3] 셀프조인(self join)
-- 직원 정보
create table tblSelf
(
  seq number primary key--직원번호
  name nvarchar2(5not null--직원명
  depart nvarchar2(10not null--부서명
  
  --super number not null --직속상사(***)
  super number null references tblSelf(seq) --자기 자신을 참조(FK), 반드시 null
);
 
insert into tblSelf values (1'홍사장''총무부'null);
insert into tblSelf values (2'김부장''총무부'1);
insert into tblSelf values (3'최부장''엽업부'1);
insert into tblSelf values (4'박과장''엽업부'3);
insert into tblSelf values (5'유대리''영업부'4);
insert into tblSelf values (6'이사원''영업부'5);
 
select * from tblSelf;
 
-- 직원 명단을 출력하시오.
select * from tblSelf;
 
select s2.name as "직원명", s1.name as "상사명"  from tblSelf s1
    inner join tblSelf s2
        on s1.seq = s2.super; -- PK=FK, 상사가 없는 홍사장은 제외
 
select s2.name as "직원명", nvl(s1.name, '상사없음') as "상사명"  from tblSelf s1
    right outer join tblSelf s2
        on s1.seq = s2.super; -- 홍사장 포함 출력
 
 
 
 
 
 
-- Union
--  1. join
--  : 1개 이상의 테이블 컬럼을 하나의 결과셋으로 반환 -> 컬럼합치기
--  2. union
--  : 2개 이상의 결과셋을 하나의 결과셋으로 반환 -> 레코드 합치기
 
select * from tblCountry where cont = 'AS'--행 4개
select * from tblCountry where cont = 'EU'--행 3개
 
select * from tblCountry where cont = 'AS'
union
select * from tblCountry where cont = 'EU';
 
 
-- 게시판 운영
--  : 3년간(2013 - 30000건, 2014 - 50000건, 2015 - 100건)
create table board2013
(
  seq number primary key--글번호
  name nvarchar2(10not null--글쓴이
  content varchar2(2000not null --글내용
);
 
create table board2014
(
  seq number primary key--글번호
  name nvarchar2(10not null--글쓴이
  content varchar2(2000not null --글내용
);
 
create table board2015
(
  seq number primary key--글번호
  name nvarchar2(10not null--글쓴이
  content varchar2(2000not null --글내용
);
 
insert into board2013 values (1'홍길동''2013년 글입니다.1');
insert into board2013 values (2'아무게''2013년 글입니다.2');
insert into board2013 values (3'호호호''2013년 글입니다.3'); --2013, 3만건
 
insert into board2014 values (4'홍길동''2014년 글입니다.1');
insert into board2014 values (5'아무게''2014년 글입니다.2');
insert into board2014 values (6'호호호''2014년 글입니다.3'); --2014, 5만건
 
insert into board2015 values (3'호호호''2015년 글입니다.3'); --2015, 1백건
 
select * from board2015
select * from board2014
select * from board2013;
 
-- 년도에 상관없이 모든 게시물을 한꺼번에 보고싶다!!!
 
select * from board2015
union
select * from board2014
union
select * from board2013;
 
 
 
 
--문제
-- 1. 입사월별로 인원수를 구하시오. (몇월, 몇명 입사?) group by, count, to_char
-- 출력
-- [월]    [인원수]
--  1월      20
--  2월      25
--  3월       7
select to_char(ibsadate, 'MM') as 월, count(*) as 인원수  
  from insa group by to_char(ibsadate, 'MM')
    order by to_char(ibsadate, 'MM') asc;
 
-- 2. 기본급+수당 가장 많은 사람이 누구? (이름, 기본급+수당), 서브쿼리
select name, basicpay+sudang from insa where basicpay+sudang in (select max(basicpay + sudang) from insa);
 
-- 3. 부서별 급여합을 구하시오.
select buseo, sum(basicpay) from insa group by buseo; 
-- 3. 직위별 급여합을 구하시오.
select jikwi, sum(basicpay) from insa group by jikwi; 
 
-- 4. 부서별 인원수를 구하되.. 총 인원이 5명 이상인 결과만 출력하시오. group by, having
select buseo, count(*from insa group by buseo having count(*>= 5;
 
-- 5. 성씨가 1자리 : 성씨별 인원수 출력(성, 인원수) group by
select distinct substr(name, 11), count(*from insa group by substr(name, 11);
 
-- 6. 성별 인원수? (남자 몇명? 여자 몇명?)
 
-- 7. 부서별 남자직원수가 5명 이상인 부서와 그 인원수? (4문제와 비교)
 
-- 8. 입사년도별 인원수(ex) 2000년 5명, 2001년 6명, 2002년 2명..)
select to_char(ibsadate, 'YYYY'), count(*from insa group by ibsadate; --ing
 
-- 9. 기본급여 평균 이하인 사원 출력(이름, 기본급)
 
-- 10. 전체인원수, 2000년, 1999년, 1998년도에 입사한 직원수를 다음의 형식으로 출력. decode, count
--  [전체]    [2000]    [1999]    [1998]
--     60        12         8         4
 
cs


* 테이블 만들기
- primary key(PK)
- 테이블 삭제
- 자동 증가 번호 제공 객체 :
- insert
- 데이터 삭제
- 데이터 수정
- 컬럼의 순서
* group by
* having ****
* 서브 쿼리
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
--테이블 생성
 
-- 메모 테이블
 
-- 1. 엔티티(속석) 정의
--  메모(번호, 내용, 작성자, 작성시간)
 
-- 2. 설계
--  a. 번호 : 숫자, 식별자(***), NN, ND      1, 2.. m01, m02.. AB0011
--  b. 내용 : 문자열(2000), NN
--  c. 작성자 : 문자열(5), NN
--  d. 작성시간 : 날짜, NN
 
-- 3. 구현
--  1,2번의 결과를 실제 데이터베이스에 구현(구축)하는 단계 -> SQL 사용
 
 
-- SQL(시퀄), Query
 
create table 테이블명
(
  --테이블 스키마 선언(컬럼구성, 선언)
  컬럼정의,
  컬럼정의,
  
  컬럼명 자료형 제약사항,
  컬럼명 자료형(길이) 제약사항
);
 
 
create table memo
(
  -- 기본키(기본컬럼, 테이블의 식별자 역할 : 행과 행을 유일하게 구분할 수 있는 값을 가지는 컬럼)   **가장역할
  --  a. 테이블내에서 레코드 구분 식별자
  --  b. 중복값을 가질 수 없다. ND
  --  c. Null을 가질 수 없다. NN
  seq number primary key--(NN,ND)
  
  memo varchar2(2000not null--필수값(NN)
  
  name nvarchar2(5not null,
  
  regDate date not null
);
 
 
desc table memo;
 
 
 
 
-- 테이블 삭제(데이터 포함)
--create로 생성한 테이블은 drop으로 삭제한다.
drop table memo; 
 
 
 
 
-- ex)메모2
create table memo
(
  seq number primary key--기본키
  memo varchar2(2000),
  
  --name nvarchar2(5) null, --null 허용 컬럼(비워둘 수 있다.) //익명허용
  -- default '익명' : 기본값**
  -- 컬럼의 기본값
  --  : 사용자가 값을 넣으면 그 값이 대입되고
  --    사용자가 값을 넣지 않으면 기본값이 대신 대입된다.
  name nvarchar2(5default '익명' null,
  
  regDate date default sysdate not null --데이터가 추가되는 시간이 글쓴 시간
);
 
 
 
 
-- ex)메모3
create table memo
(
  seq number primary key,
  memo varchar2(2000not null,
  name nvarchar2(5null,
  regDate date default sysdate not null
);
 
-- 메모 추가
-- 자동 증가 번호 제공 객체(넘버링)
-- 시퀀스 객체 : 테이블에 종속적이진 않다.
create sequence memoSeq;
drop sequence memoSeq;
 
select memoSeq.nextVal from dual;
select 'm' || memoSeq.nextVal from dual;
 
-- 상품번호 ABFC1220.,
 
 
 
 
--실제로 만들어보기
create table memo
(
  seq number primary key,
  memo varchar2(2000not null,
  name nvarchar2(5not null,
  etc varchar2(1000default '비고없음' null,
  regDate date default sysdate not null
);
 
 
-- 테이블에 데이터 추가하기
-- insert 문
--  : 레코드를 추가하기(행단위 입력)
--- insert into 테이블명 (컬럼리스트) values (값리스트);
 
insert into memo(seq, memo, name, etc, regDate) 
  values (1'메모입니다''홍길동''테스트''2015-01-09');
 
select * from memo; --확인
 
 
--primary key 컬럼
--에러]unique constraint (%s.%s) violated
insert into memo(seq, memo, name, etc, regDate) 
  values (1'메모입니다''홍길동''테스트''2015-01-09');
 
 
--컬럼 중 null을 허용, not null
insert into memo(seq, memo, name, regDate) 
  values (3'메모입니다''홍길동''2015-01-09'); --암시적으로 null 입력
 
insert into memo(seq, memo, name, etc, regDate) 
  values (4'메모입니다''홍길동''null''2015-01-09'); --명시적으로 null 입력
 
 
--에러]not null, cannot insert NULL into (%s)
insert into memo(seq, memo, etc, regDate) 
  values (5'메모입니다''null''2015-01-09'); --암시적
  
insert into memo(seq, memo, name, etc, regDate) 
  values (6'메모입니다'null'null''2015-01-09'); --명시적
 
 
select seq, to_char(regDate, 'YYYY-MM-DD-HH24-MI-SS'from memo;
--where ibsadate >과<의 경우 '2015-01-01' 특성 고려하기
 
 
-- 컬럼의 순서
-- 컬럼의 순서와 값의 순서는 반드시 같아야 한다.
 
 
 
 
 
-- default
insert into memo(seq, memo, name, etc) 
  values (9'메모입니다''홍길동''테스트'); --암시적(생략해되는, 안정적),,, date를 지워도 뜬다
  
insert into memo(seq, memo, name, etc, regDate) 
  values (10'메모입니다''홍길동''테스트', sysdate); --직접 대입
 
insert into memo(seq, memo, name, etc, regDate) 
  values (11'메모입니다''홍길동''테스트'default); --명시적*** null과 비슷한 상황
 
 
 
 
--시퀀스 객체
select memoSeq.nextVal from dual;
select memoSeq.currVal from dual; --**
 
insert into memo(seq, memo, name, etc, regDate) 
  values (memoSeq.nexVal, '메모입니다''홍길동''테스트'default);
 
 
 
 
 
--insert 생략 표현
--  : 컬럼 리스트를 생략할 수 있다. (테이블에 가서 직접 확인)
--  : 가독성 낮음
--  : 값리스트의 순서는 테이블 원본 컬럼의 순서와 동일(***********)
--  : null값이나 default값을 생략할 수 없다.(***********)
insert into memo values (memoSeq.nextVal, '메모''홍길동''비고', sysdate); --원본
insert into memo values ('메모', memoSeq.nextVal, '홍길동''비고', sysdate); --순서변경x
insert into memo values (memoSeq.nextVal, '메모''홍길동''비고'); --생략x
 
 
 
 
 
-- 데이터 수정, update
--  : 컬럽값(데이터)를 수정한다.
-- update 테이블명 set 컬럼명=값, 컬럼명=값, 컬럼명=값;
-- update 테이블명 set 컬럼명=값, 컬럼명=값, 컬럼명=값 where 절; ******조건을 찾아 바꿔야.,
 
update memo set name = '하하하'--9개 행 이(가) 업데이트되었습니다. --문제?.. 모두 바꿔버린다.
update memo set memo = '메모입니다!';
update memo set memo = '메모입니다!!!!' where seq=1;--'1개' 행 이(가) 업데이트되었습니다.
 
--여러 컬럼값 수정
update memo set name= '호호호', etc = '임시' where seq=1;
 
--null값, default값 수정
update memo set etc=null, regDate=default where seq=1;
 
 
select * from tblCountry;
 
--기존 면적에서 +10씩..
update tblCountry set area += 10--x
update tblCountry set arear = area+10--o
 
 
 
 
 
-- 데이터 삭제, delete
--  : 레코드 삭제(행단위 삭제)
--  : 셀 삭제 -> 업데이트(null)
 
-- delete [from] 테이블명 [where절];
delete from memo where seq=6;
delete from memo where etc is null;
 
delete from memo; --모든 데이터 삭제
drop table memo; --데이터+테이블 삭제
 
select * from memo; --확인
rollback; --실행x
 
 
 
 
 
-- group by
--  : 특정 컬럽값을 대상으로.. 중복값이 발생하면.. 그 중복값을 기준으로 그룹을 형성
--  : 그룹 짓는 이유? -> 그룹별로 집계 함수를 적용하기 위해서(********)
--  : 그룹별로 통계값을 구하는 작업을 할 때 사용한다.(********)
--  : group by + 집계함수
--  : where절 group by절 order by절
--  : select 대상(집계함수 결과, group by 대상컬럼) - 그 이외의 단일컬럼들은 사용 불가능!!
 
 
select * from insa;
--부서별 평균 월급?
select avg(basicpay) from insa; --전직원 평균 월급(155만원)
select distinct buseo from insa; --부서찾기
select avg(basicpay) from insa where buseo='총무부'--171
select avg(basicpay) from insa where buseo='개발부'--138
select avg(basicpay) from insa where buseo='영업부'--160
select avg(basicpay) from insa where buseo='기획부'--185
select avg(basicpay) from insa where buseo='인사부'--153
select avg(basicpay) from insa where buseo='자재부'--141
select avg(basicpay) from insa where buseo='홍보부'--145 번거로운 작업..
 
select buseo, trunc(avg(basicpay)) from insa group by buseo; --한방에!***
select buseo, trunc(avg(basicpay)), name from insa group by buseo; --집계함수와단일함수는 표현x
 
 
--지역별로 사는 직원수?
select city, count(*), trunc(avg(basicpay)), max(ibsadate), min(ibsadate) from insa
      group by city;
      
--대륙별 국가 몇개?
select cont, count(*from tblCountry group by cont;
 
 
select * from insa;
 
 
 
-- having
--  ***********
-- select -> 조건 -> where절     : 단일 레코드 조건
-- group by -> 조건 -> having절  : 집합 함수의 결과에 대한 조건
 
-- 부서별 평균 월급
select buseo, avg(basicpay) from insa group by buseo;
 
-- 부서별 평균 월급이 150만원이 넘는 결과만 출력
select buseo, avg(basicpay) from insa group by buseo having avg(basicpay) >= 1500000--**
-- 직원들 중 월급이 150만원이 넘는 직원들만을 대상으로 부서별 평균월급?
select buseo, avg(basicpay) from insa where basicpay >= 1500000 group by buseo;
 
-- 부서의 직원이 10명이 넘는 부서만 가져오기
select buseo, count(*from insa group by buseo having count(*>= 10;
 
select buseo, count(*from insa group by buseo having city = '서울';
select buseo, count(*from insa group by buseo having buseo > '다'--해빙 응용 바꿔보기
 
 
 
 
 
-- 서브 쿼리, Sub Query, 하위 쿼리
--  : 쿼리 안에 또 다른 쿼리가 있는 형태
--  : select문 안에 selcet문
 
-- 인구수가 가장 많은 나라의 이름?
select * from tblCountry order by popu desc;
 
select name, max(popu) from tblCountry; --120660 x
select * from tblCountry where popu = 120660;
 
select name from tblCountry where popu = max(popu);
 
select name from tblCountry where popu = (select max(popu) from tblCountry); --***
 
 
-- 직원 중 월급이 가장 많은 직원명?
select max(basicpay) from insa; --2650000
select name, basicpay from insa where basicpay = 2650000;
 
select name, basicpay from insa where basicpay = (select max(basicpay) from insa); --***
select name, basicpay from insa where basicpay = (select min(basicpay) from insa);
select name, basicpay from insa where basicpay >= (select avg(basicpay) from insa);
 
 
 
-- 서브쿼리 사용시.,
-- 1. 서브쿼리의 결과값이 1개일때.,
-- 2. 서브쿼리의 결과값이 여러개일때.,
 
-- 수당을 20만원 이상받는 직원들이 소속된 부서의 직원명단을 출력?
select * from insa where sudang >= 200000;
select distinct buseo from insa where sudang >= 200000;
 
select * from insa where buseo in ('총무부''개발부''영업부''기획부''인사부'); --48
select * from insa where buseo in (select distinct buseo from insa where sudang >= 200000); --48**
 
 
 
 
cs


* 집계함수
1. count : 갯수
- 함수의 결과는 반드시 별칭을 지정할 것*******
- 함수의 결과는 단일 데이터와 동시에 select 작업 불가능*******
2. sum : 합계 오로지 숫자컬럼만
3. avg : 평균
- null컬럼값이 제외****
4. max : 최대
5. min : 최소
* 숫자함수
- round : 반올림
- floor, trunc : 무조건 내림
- ceil : 무조건 올림
- mod : 나머지 함수
* 문자열 함수
- upper, lower, initcap : 대소문자변환
- substr : 추출, char substr(컬럼명, 시작위치, 갯수)**
- length : 길이
- replace, tranlate : 치환
- decode :문자열 치환**
* 날짜 함수
- sysdate
- last_day
- add months
* 형변환 함수
- 숫자->문자 : to_char()
- 날짜->문자 : to_char(날짜, 형식문자열) ******
- 문자->날짜 : to_date(문자, 형식문자열)

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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
 
-- SQL 함수
 
-- 1. 집계함수 (******)
--  a. count  : 갯수
--  b. sum    : 합계
--  c. avg    : 평균
--  d. max    : 최대
--  e. min    : 최소
 
 
 
 
 
-- a. count 함수
--  : number count(컬럼명)
--  : 해당 컬럼의 값이 총 몊개인지 반환 -> 행의 갯수 반환
--  : null값을 가지는 행은 제외
 
select * from tblCountry;
 
-- 국가가 총 몇개국입니까?(행의 갯수)
select count(*from tblCountry; --14개국
select count(name) from tblCountry; --14
 
-- 인구수가 조사된 나라의 갯수?(null 제외)
select count(popu) from tblCountry; --13
select count(*from tblCountry where popu is not null
 
-- 인구수가 조사 안 된 나라의 갯수?
select count(*from tblCountry where popu is null
 
-- 서울에 사는 직원이 몇 명?
select count(*from insa where city = '서울';
 
-- 컬럼은 1개 또는 * 만 넣을 수 있다. 
select count(name, capital) from tblCountry; --표현x,
 
-- 회사(insa)에서 연말 보너스 1000000000원 -> 1/n -> 1억/사원수
select 100000000 /count(*from insa;
 
-- 국가테이블의 대륙이 몇 종류?(갯수)
-- count로 묶어만 주면 됨.,
select distinct cont from tblCountry;
select count(distinct cont) from tblCountry;
 
-- 회사에 몇개의 부서가?
select distinct buseo from insa;
select count(distinct buseo) from insa;
 
-- ******함수의 결과는 반드시 별칭을 지정할 것
-- ******함수의 결과는 단일 데이터와 동시에 select 작업 불가능
select count(*), name from insa;
 
 
 
 
 
-- b. sum 함수
--  : number sum(컬럼명)
--  : 해당 컬럼값의 종합을 반환
--  : 숫자 컬럼
 
select popu from tblCountry;
 
-- 국가테이블의 모든 나라의 인구 총합은 몇 명?
select sum(popu) from tblCountry; 
select sum(name) from tblCountry; --에러]invalid number
select sum(*from tblCountry; --x 
 
select sum(popu * 2), sum(popu) from tblCountry;
 
-- 총무부 직원들의 총 급여 합은?
select sum(basicpay) from insa where buseo = '총무부';
 
-- 총무부 직원들의 평균 급여는?
select sum(basicpay) / count(*from insa where buseo = '총무부';
 
 
 
 
 
 
-- c. avg 함수
--  : number avg(컬럼명)
--  : 해당 컬럼값이 평균값 반환
--  : null컬럼값이 제외(***)
--  : 숫자 컬럼
 
 
-- 평균 인구수? ..null의 여부
select popu from tblCountry;
 
select sum(popu) from tblCountry; --202652
select count(*from tblCountry; --14
select sum(popu)/ count(*from tblCountry; -- 202652 / 14
 
 
select avg(popu) from tblCountry; --15588
select sum(popu) / count(popu) from tblCountry; --15588
 
 
 
 
-- d. max, min 함수
--  : number mas(컬럼명)
--  : number min(컬럼명)
--  : 숫자 컬럼
 
-- 인구수가 가장 많은 나라의 인구는 몇 명?
select max(popu) from tblCountry;
select max(popu), name from tblCountry; --x
 
select max(name) from tblCountry;
 
--가장 적은 나라의 인구수
select min(popu) from tblCountry;
 
 
select count(*) as "총 직원수"
      , sum(basicpay) as "총 월급"
      , avg(basicpay) as "평균 월급"
      , min(ibsadate) as "최고참의 입사날짜" --작은것이 빠른
      , max(ibsadate) as "신입의 입사날짜"
      , months_between(min(ibsadate), max(ibsadate)) / 12 as "최고참vs신입의 연차"
from insa;
 
 
-- ****** 집계함수는 일반컬럼과 동시에 select 불가능
-- ****** 집계함수는 where에서 사용불가 -> where 적은 단일 레코드에 대한 질문(조건)
 
select max(basicpay) from insa; --최고급여.. 누군지 알고싶다!
select name from insa where basicpay = max(basicpay); --x,,where절은 집합 함수를 못 씀.
select name from insa where basicpay = 2650000--해결!직접 상수를 입력.
 
 
 
 
 
 
 
 
-- 숫자함수
 
-- a. round 함수
--  : 반올림
--  : number round(숫자)
--  : number round(숫자, 자릿수)
 
select 3.45678 from dual; --원본
select round(3.45678from dual; --정수, 3
select round(3.456780from dual; --정수, 3
select round(3.456781from dual; --3.5
select round(3.456782from dual; --3.46
 
select avg(basicpay) from insa;
select round(avg(basicpay)) from insa; --***
 
 
 
 
-- b. floor, trunc 함수
--  : 절삭, 무조건 내림
--  : 반올림 o,x -> x
--  : number floor(컬럼명)
--  : number trunc(컬럼명 [,자릿수])
--  : 현재 숫자와 가장 가까운 '적은 정수 중' 최대 정수를 반환한다.
 
select 4.5678 from dual;
select floor(4.5678from dual; --정수, 4
select trunc(4.5678from dual; --4
select trunc(4.56781from dual; --4.5
 
 
 
 
-- c. ceil 함수
--  : 무조건 올림
-- number ceil(컬럼명)
-- 현재 숫자와 가장 가까운 정수를 반환한다.
 
select 4.123 from dual;
select ceil(4.123from dual; --5
select ceil(4.000001from dual; --5
 
--언제쓰느냐?... 페이징
select 75/20 as 총페이지 from dual;
select ceil(75/20) as 총페이지 from dual;
 
select 61/20 as 총페이지 from dual;
select ceil(61/20) as 총페이지 from dual;
 
 
 
 
-- d. mod 함수
--  : 나머지 함수(%연산자)
--  : number mod(피제수, 제수)
 
-- 10 % 3
select mod(103from dual;
 
--100분은 몇시간 몇분?
-- : 100/60 -> 몫(시)
-- : 100/60 -> 나머지(분)
select trunc(100/60) as "시", mod(100,60) as "분" from dual;
 
 
 
 
 
 
-- 문자열 함수
 
--  a. upper, lower, initcap 함수
 
select first_name from employees;
select first_name, upper(first_name), lower(first_name) from employees; -- 대소문자 변환
 
-- 이름중에 'EL' 들어간 사람? 
select * from employees where first_name like '%EL%';
select * from employees where first_name like '%el%'--대소문자..?
select * from employees where lower(first_name) like '%el%'--***
 
selet 'test' from dual;
select initcap('test'from dual; --앞글자만 대문자로 변화
 
 
 
 
-- b.  substr 함수
--  : 문자열 추출
--  : 서수가 1부터 시작
--  : 두번째 매개변수가 문자열의 갯수
--  : char substr(컬럼명, 시작위치, 갯수)**
 
select '가나다라마바사아자차' from dual;
select substr('가나다라마바사아자차'23from dual;  --시작위치에서 갯수만큼.,
select substr('가나다라마바사아자차'2from dual;     --시작위치에서 끝까지., (갯수 설정x)
select substr('가나다라마바사아자차'-2from dual;    --끝에서부터 갯수만을.,
 
 
select name from insa;
 
--이름 가져오기
select substr(name, 11) as "성"
        , substr(name, 2) as "이름"
          from insa;
          
--회사에 여직원이 몇명?
select * from insa;
 
select * from insa where substr(ssn, 8 ,1= '2';
select count(*from insa where substr(ssn, 8 ,1= '2'--29
select count(*from insa where substr(ssn, 8 ,1= '1'--남자직원수 31
 
--회사에 어떤 성씨가 있냐?
select name from insa;
select distinct name from insa;
select distinct substr(name, 11from insa;
select count(distinct substr(name, 11)) from insa; --추가] 몇종류의 성씨가 있나?
select count(distinct substr(name, 11)) from insa where city = '서울';
 
 
 
 
 
 
-- c. length 함수
--  : 문자열 길이
 
select name, length(name) from tblcountry;
select name, length(name) from tblcountry where length(name) = 2--나라 이름 2글자인 나라?
select name, length(name) from tblcountry order by length(name) desc; --나라이름이 긴 나라부터?
 
 
 
 
-- d. replace, tranlate 함수
--  : 문자열 치환
--  : translate -> 1글자 -> 1글자
--  : repalce -> 문자열 -> 문자열
 
select name, translate(name, '홍''김'), replace(name, '길동''하하'from insa;
 
-- e. decode 함수**
--  : 문자열 치환
select cont from tblCountry;
select replace(cont, 'AS''아시아'from tblCountry; --as만 이사로 치환
select replace(replace(replace(replace(replace(cont, 'AS''아시아')
                , 'SA''남아메리카')
                  , 'EU''유렵'
                    , 'AF''아프리카')
                      , 'AU''호주'from tblCountry; --이st..불편해..!
                      
                      
select decode(cont, 'AS''아시아'from tblCountry; --바꿀게 없으면 null을 반환시킴*
select decode(cont, 'AS''아시아'
                    ,'EU''유럽'
                    ,'SA''남아메리카'
                    ,'AF''아프리카'
                    ,'AU''호주'from tblCountry; -- 한방에 치환! ***
                    
--아시아에 속한 나라는 몇개국?
select count(decode(cont, 'AS''아시아')) from tblCountry; 
select count(*from tblCountry where cont = 'AS'--정석
 
--아시아 몇개국? 유럽 몇개국?
select count(*from tblCountry where cont = 'AS';
select count(*from tblCountry where cont = 'EU';
select count(*from tblCountry where cont = 'AS' or cont = 'EU'--이런 답변nono..
 
select count((cont, 'AS''아시아')) from tblCountry;
select decode((cont, 'EU''유럽')) from tblCountry;
select count(decode(cont, 'AS''아시아')), count(decode(cont, 'EU''유럽')) from tblCountry; --한방에! ***
 
 
--김씨 몇명? 박씨 몇명 ? 최씨 몇명?
select count(*from insa where substr(name, 11= '김';
 
select decode(substr(name, 11), '김''1'from insa;
select count(decode(substr(name, 11), '김''1'))
        ,count(decode(substr(name, 11), '박''1'))
        ,count(decode(substr(name, 11), '최''1')) from insa; --한방에! ***
        
        
        
        
        
                
-- 날짜 함수
 
-- a. sysdate
--  : 현재 시간 가져오기
select sysdate from dual;
 
 
select * from insa where ibsadate > sysdate; --앞으로 해야하는 일정
 
 
 
-- b. last_day
--  : 해당 날짜의 월의 마지막 일
 
--2015년 1월은 몇일까지 있나?
select last_day(sysdate) from dual; 
 
 
 
-- c. months_between
--  : 날짜 간격
 
 
 
-- d. add months
--오늘부터 3개월 후는 어떤날짜?
select sysdate, add_months(sysdate, 3from dual;
 
 
 
 
 
 
-- 형변환 함수
--  1. 숫자 -> 문자
--  2. 날짜 -> 문자
--  3. 문자 -> 문자
--  4. 문자 -> 날짜
 
 
 
-- 1. 숫자 -> 문자
-- to_char() 함수
--  : char to_char(숫자, 형식문자열)
 
-- name like '김__'
 
-- 형식문자열
--  1. 9  : 숫자 1자리
--  2. 0  : 숫자 1자리
--  3. $  : 달러표시
--  4. L  : 로케일 통화(원)
--  5. .  : 소숫점 표시
--  6. ,  : 천단위 표시
 
 
-- 100-> '100'
select to_char(100'999'from dual; --'100'
select to_char(100'000'from dual; --'100'
select to_char(10'999'from dual; --'10'
select to_char(10'000'from dual; --'010'
 
select to_char(1'999'from dual; -- '1' 데이터만 출력
select to_char(1000'999'from dual; -- '####'
 
select to_char(1'000'from dual; --'001'
select to_char(1000'000'from dual; --'####'
 
-- $, L
select to_char(1000'9999'from dual;
select to_char(1000'$9999'from dual;
select to_char(1000'9999원'from dual; --x
select to_char(1000'9999'|| '원' from dual;
select to_char(1000'L9999'from dual;
 
-- .
select to_char(123.456'999.999'from dual;
select to_char(123.456'999.99'from dual; --123.46
select to_char(123.456'999.9'from dual; --123.5
select to_char(123.456'999'from dual; --123
 
-- ,
select to_char(1000'9999'from dual;
select to_char(1000'9,999'from dual;
select to_char(1000'99,99'from dual;
select to_char(1000'999,9'from dual;
 
select to_char(1000000'9,999,999'from dual;
 
 
 
 
 
-- 1. 날짜 -> 문자 (**********)
--  : date -> char
--  : char to_char(날짜, 형식문자열)
 
-- 형식문자열
-- 1. YYYY        : 년도 4자리 ***
-- 2. YY          : 년도 2자리
-- 3. MONTH       : 월 단어(풀네임)
-- 4. MON         : 월 단어(약어)
-- 5. MM          : 월 2자리(숫자) ***
-- 6. DAY         : 요일 단어(풀네임)
-- 7. DY          : 요일 단어(약어)
-- 8. DDD, DD, D  : 날짜 DD
-- 9. HH, HH24    : 시 ***
-- 10. MI         : 분 ***
-- 11. SS         : 초 ***
 
 
select sysdate, to_char(sysdate, 'YYYY'), to_char(sysdate, 'YY'from dual; --2015
select to_char(sysdate, 'MONTH'from dual; --1월
select to_char(sysdate, 'MON'from dual; --1월
select to_char(sysdate, 'MM'from dual; --01
select to_char(sysdate, 'DAY'from dual; --목요일
select to_char(sysdate, 'DY'from dual; --목
select to_char(sysdate, 'DDD'from dual; --008 (1월 1일부터 누적된 날짜가 출력, 년기준)
select to_char(sysdate, 'DD'from dual; --08 (월기준)
select to_char(sysdate, 'D'from dual; --5 (주기준, 일-1, 토-7)*
select to_char(sysdate, 'HH'from dual; --01(12시)
select to_char(sysdate, 'HH24'from dual; --13(24시)
select to_char(sysdate, 'MI'from dual; --04
select to_char(sysdate, 'SS'from dual; --01
 
 
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD'FROM DUAL;
 
 
 
-- 출력용 & 조건
-- 입사년도가 1999년 직원만 출력
select * from insa;
select * from insa where to_char(ibsadate, 'YYYY'= '1999';
--입사년도 12월인 사람?
select * from insa where to_char(ibsadate, 'MM'= '12'
 
--97, 98, 99년도 입사한 사람?
select * from insa where ibsadate between '1997-01-01' and '1999-12-31'--between
select * from insa where to_char(ibsadate, 'YYYY') in ('1997''1998''1999'); --to_char, in
 
 
 
 
-- 3. 문자 -> 숫자
--  java : integer.parseInt("100") -> 100
 
-- to_number 함수
--  : number to_number(문자)
 
select '123' from dual;
select to_char(sysdate, 'YYYY'from dual; --'2015'
 
select '123' from dual;
select '123' + 100 from dual; --223, 가능o, 권장x
select '123' || 100 from dual; --123100
 
select to_number('123'+ 100 from dual; --이렇게..
 
 
 
-- 4. 문자 -> 날짜
 
-- to_date 함수
-- : date to_date(문자, 형식문자열)
 
-- 형식문자열
-- : to_char()에서 사용하던 형식문자열과 동일하게 사용
 
select '2015-01-08' from dual; --string
select sysdate from dual;
select * from insa where ibsadate < '2015-01-05';
 
select to_date('2015-01-08''YYYY-MM-DD'from dual;
 
select to_date('2015-01-08 1:44:50''YYYY-MM-DD HH24:MI:SS'from dual; --*******
 
 
 
 
-- nvl함수
--  : null value 함수
--  : 특정 컬럼이 null이면 대신할 값을 치환 함수
--  : nvl(컬럼명, 대체값)
--  : 대체값은 컬럼값과 동일한 자료형
 
select name, popu from tblCountry;
select name, nvl(popu, 0from tblCountry; --null->0으로 치환
 
select namem tel from insa;
select name, nvl(tel, '(연락처 미기재)'from insa;
 
 
cs



* 별칭  : as 컬럼명

* 조건절

1. where 

2. between : 범위지정

3. in : 열거

4. like : 패턴검색, '김__'/'김%'

5. distinct : 중복값 제거

6. null 조건 : null상태 검사, is null/is not null

7. order by : 정렬, asc/desc

8. months_between : 날짜


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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
 
-- 컬럼 리스트
-- : 테이블로부터 가져올 컬럼 명단
-- : 컬럼명 or *(모든 컬럼)
 
desc table tblCountry;
 
select * from tblCountry; --결과 테이블, 결과셋, Resultset, 레코드셋(Record Set)
select name from tblCountry; --단일 컬럼
select name, capital from tblCountry; --2개
select name, area * 2 from tblCountry; --연산 가능
select name, name from tblCountry; --중복 컬럼
select name, '수도 : ' || name from tblCountry; --중복 컬럼
select name, name, area, area*2 from tblCountry;
 
 
-- 결과셋의 컬럼명의 별칭(Alias) 붙이기 
--  : 컬럼명 as 별칭
--  : 컬럼명 as "별칭"
--  : 자바에서는 별칭을 인식한다. 의미있게 짓기 
select name, name as 국가명, area, area*2 as 면적 from tblCountry;
select name as name2 from tblCountry;
select name as "나라 이름" from tblCountry; --공백 (추천x)
select name as "select" from tblCountry; --예약어 사용 (추천x)
 
 
 
 
 
-- 상수 표현
-- 1. 숫자 상수
--  : 10
--  : 2.5
 
-- 2. 문자(열) 상수
--  : '문자열' (o)
--  : "문자열" (x)
 
-- 3. 날짜/시간 상수
--  : '2014-01-10' <- date 타입 (문맥에 따라 다름)
--  : '2014년 월 10일' <- 지원(x)
 
 
 
-- 문자열 연산자
--  : 문자열 + 문자열 <- concat
--  : '문자열' || '문자열'
select '국가명 : ' || name as 국가명 from tblCountry;
select '국가명 : ' + name as 국가명 from tblCountry; --사용x
 
select * from employees;
select first_name || '' || last_name as name from employees;
 
 
-- select는 상수나 연산의 결과나 함수의 결과를 출력
select 10;
select 10 from employees;
select 10 from dual; --가상 테이블
 
select 10 + 20 from dual; --별 쓸모 없는.,
select sysdate from dual; --현재 시간 얻어오기
 
 
 
 
-- 연산자
-- 1. 산술 연산자
--  : +, -, *, /
 
-- 2. 비교 연산자
--  : >, >=, <, <=, =(==), <>(!=)
 
-- 3. 논리 연산자
--  : and(&&), or(||), not(!)
 
-- 4. 문자열 연산자
--  : ||
 
-- 5. SQL 연산자(java : obj instanceof class)
-- : in, between, like, is null, not null, any, all.,
 
 
-- select 컬럼리스트 from 테이블 where절 order by절
-- 1. 컬럼 리스트
--  : 원하는 컬럼만 가져오기
--  : 수직 필터링
 
-- 2. where 절★★
--  : 원하는 행만 가져오기
--  : 수평 테이블
--  : 주로 비교연산식, 논리연산식을 사용, 함수를 사용
 
select * from tblCountry --모든 행(14행)
select * from tblCountry where 행을 구분하기 위한 조건;
select * from tblCountry where cont = 'AS';
select * from tblCountry where area >= 500;
select * from tblCountry where area < 500;
 
 
 
-- ask] 인구수가 5000이 넘는 나라의 국가명과 인구수를 가져오시오.
select * from tblCountry; --1.모든 데이터(원본) 가져와서 확인하기
select name, popu from tblCountry where popu >= 5000;
 
-- ask] 동시에 가져오는 거 어떻게?
-- 1. 면적(area)이 100 초과하는 나라의 국가명(name)과 면적(area)을 출력하시오.
select name, area from tblCountry where area > 100;
 
-- 2. 아시아(AS) 대륙에 속한 국가명(name)을 출력하시오.
select name from tblCountry where cont = 'AS';
 
-- 3. 아시아와 유럽에 속한 국가명을 출력하시오.
select name from tblCountry where cont = 'AS' or cont = 'EU';
 
-- 4. 아시아에 속하지 않는 국가명을 출력하시오.
select name from tblCountry where cont <> 'AS';
 
-- 5. 인구수가 10000 이상이고 면적이 100이상인 국가명, 인구수, 면적을 출력하시오. 
select name, popu, area from tblCountry 
  where popu >= 10000 and area >=100;
 
 
 
 
-- insa 테이블
desc table insa; --1.구성확인하기
select * from insa; --2.데이터확인하기
 
-- 6. 기획부 직원들을 출력하시오.
select name from insa where buseo = '기획부';
 
-- 7. 서울시(city)에 사는 직원 중 직위(jikwi)가 부장인 사람의 이름(name)과 주민번호(ssn)을 출력하시오.
select name, ssn from insa where city = '서울' and jikwi = '부장'
 
-- 8. 기본급(basicpay)과 수당(sudang)을 합쳐서 1,500,000원 이상인 직원 중 서울 사람만 출력하시오.
select name from insa where basicpay+sudang>1500000 and city ='서울';
 
-- 9. 수당이 150,000원 이하인 직원 중 사원과 대리만 출력하시오.
select * from insa where (sudang <= 150000) and (jikwi ='사원' or jikwi ='대리');
 
-- 10. 수당을 제외한 기본 연봉이 2천만원 이상이며 서울에 살며 직위가 과장 이상인 사람만 출력하시오.
select * from insa where (basicsudang * 12 >= 20000000) and city = '서울' and (jikwi = '과장' or jikwi = '부장');
select * from insa where not (basicsudang * 12 >= 20000000) and city = '서울' and (jikwi = '과장' or jikwi = '부장');
 
 
-- 범위 조건
-- 1. 숫자
-- 2. 날짜/시간
-- 3. 문자(코드값 -> 숫자)
 
SELECT * FROM tblCountry where popu > 10000;
 
 
 
 
 
 
 
--between
--  : where절에서 사용(조건)
--  : 범위 지정
--  : 컬럼명 between 최소값 and 최대값 ->inclusive
 
--ex1)
SELECT * FROM tblCountry where popu >= 5000 and popu <= 10000--영국, 이집트
SELECT * FROM tblCountry where popu <= 10000 and 5000 <= popu; --영국, 이집트
 
SELECT * FROM tblCountry where popu between 5000 and 10000--비트윈으로 표현, 가독성 높음
 
--ex2)
select first_name, hire_date from employees;
--2005~2006년 사이
select first_name, hire_date from employees where hire_date >= '2005-01-01' and hire_date <= '2006-12-31';
 
select first_name, hire_date from employees 
where hire_date between '2005-01-01' and '2006-12-31'--비트윈
 
--ex3)
select * from insa where name >= '나' and name <= '사';
 
 
 
 
 
 
--in
--  : where 절에서 사용(조건)
--  : 열거형 조건(제시된 값 중 하나라도 만족하명 통과)
--  ; 컬럼명 in (열거값)
 
select * from tblCountry where cont = 'AS' or cont = 'EU'--7개
select * from tblCountry where cont in ('AS''EU');
 
select * from insa where buseo in ('기획부''총무부''영업부');
select * from insa where not buseo in ('기획부''총무부''영업부');
select * from insa where buseo not in ('기획부''총무부''영업부'); --******
 
 
 
 
 
 
-- like
--  : where절에서 사용(조건)
--  : 문자열 대상
--  : 패턴 조건(특정한 패턴을 가지는 문자열을 검색)
--  : 컬럼명 like 패턴문자열
 
-- like 패턴 요소
-- 1. _ : 임의의 문자 1개
-- 2. % : 임의의 문자 0~여러개
 
--김씨성만 출력하시오.
select * from insa where name like '김__';
select * from insa where name like '__수';
select * from insa where name like '_인_';
 
--연락처가 010으로 시작하는 사람
SELECT * FROM insa where tel like '010-____-____';
 
--직위가 *장
SELECT * FROM insa where jikwi like '_장';
 
 
--홍씨성만 출력하시오. -> (홍길동, 홍민, 홍준) -> '홍__' -> '홍%'
SELECT * FROM insa where name like '홍%';
 
--
select * from employees;
 
select * from employees where first_name like 'D%';
select * from employees where first_name like '%n';
select * from employees where first_name like '%ll%';
 
 
 
 
 
 
 
-- null 조건
--  : 해당 컬럼이 nul상태인지 검사
--  : 컬럼명 is null
--  : 컬럼명 is not null
select * from tblCountry;
 
-- 인구수가 아직 기재 안 된 나라?
SELECT * FROM tblCountry where popu = null; 표현(x)
SELECT * FROM tblCountry where popu is null;
 
-- 인구수가 기재된 나라?
SELECT * FROM tblCountry where not popu is null;
SELECT * FROM tblCountry where popu is not null--*******
 
-- 도서관 -> 대여 -> 대여날짜/반납날짜
 
SELECT * FROM insa;
SELECT * FROM insa where tel is null;
 
 
 
 
 
 
 
-- distinct
--  : 결과셋의 특정 컬럽값이 중복되면.. 중복값을 제외
--  : 컬럼리스트에서 사용
--  : distinct 컬럼명
--  : 언제쓰는지..?? -> 중복값 제거 후 출력
 
-- tblCountry 에서 대륙이 어떤것이 있습니까? 
select cont from tblCountry;
select distinct cont from tblCountry;
 
-- insa에는 어떤 부서가 있습니까?
select buseo from insa;
select distinct buseo from insa;
-- 서울사는 직원들은 어떤 부서에 근무합니까?
SELECT distinct buseo FROM insa where city = '서울';
-- 영업부 직원들은 사는곳이 어디입니까?
select distinct city from insa where buseo = '영업부';
 
-- 주의! 상황을 고려해서.. 사용(distinct와 다른 컬럼은 동시에 select x)
select distinct city, name from insa where buseo = '영업부';
 
 
 
 
 
 
 
-- order by 절
--  : 정렬
--  : 오른차순, 내림차순
--  : 정렬대상 -> 숫자, 날짜, 문자(열)
--  : 결과셋의 레코드(행)을 정렬
--  : order by 컬럼명 asc(desc)
 
-- 인구수가 적은나라부터..
SELECT * FROM tblCountry order by popu asc; --오름차순
SELECT * FROM tblCountry order by popu desc; --내림차순
 
-- 인구수가 적은 나라부터..(기재된 나라만..null 빼고)
SELECT * FROM tblCountry 
  where popu is not null 
    order by popu asc;
 
--이름을 가나다라순으로 정렬하시오.
SELECT * FROM insa order by name asc;
--입사일 신입-고참 순으로.,
SELECT * FROM insa order by ibsadate desc;
--급여와 수당이 많은 순서대로.,
SELECT * FROM insa order by basicpay + sudang desc;
 
 
 
 
 
 
-- months_between
--  : 두날짜 데이터의 차이를 구하는 함수
--  : number month_between(date, date)
--  : 두날짜 차이 -> 월(단위)
 
select '2015-01-10' - '2014-05-25' from dual;
select months_between('2015-01-10''2014-05-25'from dual; --7.5개월..
 
select * from insa;
--입사일..
select months_between(sysdate, ibsadate) from insa;
select months_between(sysdate, ibsadate) / 12 from insa;
 
 
 
 
 
--ask]
--insa 테이블
--1. 사원 연락처가 010을 사용하며 서울에 거주하는 직원의 이름, 직위, 연락처를 출력하시오.
select name, jikwi, tel from insa where tel like '010-____-____';
select name, jikwi, tel from insa where tel like '010%' and city = '서울'--t
 
--2. 이름이 '동'으로 끝나고 서울에 사는 사람?
select name from insa where name like '__동' and city = '서울';
select * from insa where name like '%동' and city = '서울'--t
 
--3. 성이 '이'씨이고 이름이 '숙으로 끝나는 사람?
select name from insa where name like '이_숙'
select * from insa where name like '이%숙'--t
 
--4. 이름에 '길'자가 들어간 사람?
select name from insa where name like '%길%';
select * from insa where name like '%길%'--t
 
--5. 여직원(ssn)의 이름과 몇 년차(months_between) 인지 출력하시오. **맞는지재검
select name, months_between(sysdate, ibsadate)/12 from insa 
  where ssn like '______-2______';
  
select name, months_between(sysdate, ibsadate) / 12 from insa 
  where ssn like '%-2%'--t
 
-- order by
--6. 입사날짜가 2000년 이후에 입사한 직원들을 고참순으로 출력? 
select name from insa 
  where ibsadate between '2000-01-01' and '2015-01-07'
    order by ibsadate desc;
    
select * from insa where ibsadate >= '2000-01-01' 
  order by ibsadate desc;--t
 
--7. 기획부 직원들을 출력 -> 신입사원순으로 출력?
select name from insa 
  where buseo = '기획부'
    order by ibsadate asc;
    
select * from insa 
  where buseo = '기획부' 
    order by ibsadate asc; --t
    
--8. 기획부/총무부/개발부 직원들을 고참순으로 출력? (in + order by)
select name from insa 
  where buseo in ('기획부''총무부''개발부'
    order by ibsadate desc;
 
 
--9. 기획부/총무부/개발부 직원들 중 입사년도가 1999년~2003년 사이인 직원들을 오래된 순으로..(in, between, order by)
select name from insa 
  where buseo in ('기획부''총무부''개발부') and 
    ibsadate between '1999-01-01' and '2003-01-01' 
      order by ibsadate desc;
      
 select * from insa 
  where buseo in ('기획부''총무부''개발부'
    and ibsadate between '1999-01-01' and '2003-12-31' order by ibsadate asc; --t
 
--10. 근무년수 16년차 이상인 사람이 근무하는 부소는 어떤 부서들이 있습니까? 부서명을 가나다순으로 정렬 (distinct, order by, months_between) **못품
select distinct buseo from insa 
  where months_between(sysdate, ibsadate) / 12 >= 16
    order by buseo asc;
 
 
 
cs


1. Oracle Database

- Enterprise Edition  : 상업용

- Express Edition     : 교육용(테스트용)

- 버전(11g) - 10g, 9i...

- 데이터베이스

- 다량의 데이터를 전문적으로 관리하는 환경(프로그램)

- Oracle, MySQL(MariaDB), MS-SQL(MS), DB2.. Access, Excel, Text

- SQL 서버


2. SQL Developer

- SQL 클라이언트 툴

- Toad, SQLGate.. 이클립스


3. exerd

- 데이터베이스 설계툴

- 모델링툴

- ER-WIN, ...




데이터베이스

1. 데이터베이스 모델링

2. 데이터베이스 설계

3. 데이터베이스 구축



데이터베이스 모델링

- 데이터베이스 작업 중 초반에 하는 작업

- 가장 중요한 작업(설계도)

- 데이터베이스 시스템을 구축하기 위해서 필요한 정보들 무엇인지 수집, 분석 -> 도식화 하는 과정 -> 결과물(ERD)

- 데이터베이스 모델링 작업 -> ERD 만드는 작업

- ERD(Entity Relational Diagram) : 엔티티 관계 다이어그램


ex) 회사 관리 프로그램

사원 관리

- 정보 : 사원명, 나이, 사원번호, 연락처 등..

-> 엔티티 : 사원(사원명, 나이, 사원번호, 연락처 등..)

-> 엔티티의 구성요소 : 속성


부서 관리

- 정보 : 부서명, 부서번호, 호실, 내선번호 등..

-> 엔티티 : 부서(부서명, 부서번호, 호실, 내선번호 등..)

-> 부서의 구성요소 : 속성(Attribute)



데이터베이스 설계

- 모델링의 결과 -> ERD -> 실제 테이블 설계

- 좀더 구체화 하는 단계

- 식별자를 구체화하거나 자료형을 지정하거나 등..



데이터베이스 구축

- 앞의 2단계 결과 -> 실체화(구축) -> Oracle에 적용

- SQL 언어 사용

create table tblMember

(

seq number primary key..

)








데이터베이스 모델링


ERD

- 엔티티 관계 다이어그램

- 데이터 모델링의 대표적인 방법

- 손, 오피스, 전문 ERD 프로그램(er-win, exerd 등..)


Entity, 엔티티

- 분류될 수 있고, 다른 Entity들에 대해서 정해진 관계를 맺을 수 있는 데이터 단위

- 폴더, 테이블

- 업무에 필요한 데이터 집합


Entity Relationship

- Entity와 Entity간의 관계

- 테이블과 테이블간의 관계


Attribute, 속성

- Entity안의 가지고 있는 세부 정보들

- 사원 엔티티(사원명, 주소, 연락처..<- 속성)

- 자바와 비교

- 클래스(엔티티)

- 멤버변수(속성)


Tuple

- Entity안의 진짜 데이터 집합

- 테이블의 행(레코드)



ERD에서 Entity와 Attribute와 Relation을 표현하는 방법

- ERD 그리기


1. Entity

- 사각형으로 표시

- 이름을 대문자

- 중복 불가능

- 보통 단수로 표시(사원O, 사원들X)


2. Attribute

- Entity안에 목록으로 표시

- 대/소문자 혼용

- 보통 단수로 표시

- 추가 사항

a. NN : Not Null (필수값)

b. ND : Not Duplicate (유일값)


1. 중복되면 안되는 것(NN, ND) -> #*속성명

2. 반드시 있어야 하는것(NN) -> *속성명

3. 있어도 되고 없어도 되는것 -> o속성명


3. Relation

- 엔티티와 엔티티간의 관계

-> 자세히 말하면 엔티티안의 속성과 다른 엔티티안의 속성간의 관계

-> 레코드와 레코드간의 관계

a. 1개의 A는 1개의 B로 구성 

b. 1개의 A는 1개 이상의 B로 구성 

c. 1개의 A는 1개 이하의 B로 구성 

d. 1개의 A는 0개 이상의 B로 구성 



ERD -> 실제 구현

1. 순공학, Forward Enginnering

설계도 -> Oracle 직접 구현

2. 역공학, Reverse Enginnering

Oracle -> 설계도



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
 
오라클 서버(서비스) 작동 여부?
1. Win + R -> services.msc
 
2. 서비스
    - OracleServiceXE        : 오라클 서버
    - OracleXETNSListener    : 오라클 클라이언트 응대
 
 
 
호스트명(오라클 서버의 주소)
    1. localhost(127.0.0.1)
    2. IP / 도메인
 
 
 
sys, system, sysdba
    - 최고 관리자 계정
개인 계정
    - 
수업용 계정
    - scott, hr
 
 
 
잠겨있는 계정 활성화 시키기
1. 관리자 로그인(접속)
2. 계정 활성화
    alter user 아이디 account unlock;

3. 비밀번호 바꾸기
    alter user 아이디 identified by 비밀번호;
 
4. 2 + 3
    alter user 아이디 identified by 비밀번호 account unlock;
 
cs


+ Recent posts