Skip to content

Latest commit

 

History

History
286 lines (239 loc) · 7.23 KB

함수.md

File metadata and controls

286 lines (239 loc) · 7.23 KB

함수

👶집계 함수

sum(컬럼명) : 합

select sum(pay) 급여합 from professor;

max(컬럼명) : 최대값


min(컬럼명) : 최소값


count(컬럼명) : 해당 칼럼 레코드 개수

  • 총 레코드수(null 값 제외)
select count(bonus), count(pay) from professor;  -- bonus: 10, pay :16 (bonus 없는 사람 존재)

count(*) : 총 레코드 수

  • null을 포함한 총 레코드수

avg(컬럼명) : 평균

  • null 값은 제외하고 나눔
  • null 포함할 시, nvl() 사용
select count(*), count(bonus), sum(bonus), avg(bonus) from professor; -- 16 10 780 78
select count(*), count(nvl(bonus,0)), sum(bonus), avg(nvl(bonus,0)) from professor; -- 16 16 780 48.75

rank : 순위

  • oracle은 null의 우선순위가 가장 높음 , null 포함 시 rank함수 결과가 이상함.
select rank(600001) within group(order by g_start desc) 
from gift; -- 5

select rank(600001) within group(order by g_start desc) 
from gift where g_start is not null; -- 4

🧑숫자 함수

round(숫자, 자릿수) : 반올림

select round(12.3456789,2), round(12.3436789,2), round(12.7456789,0), round(12.3456789,0) from dual; 
-- 12.35 12.34 13 12

ceil(숫자) : 올림

  • 정수 반환
select ceil(12.34), ceil(-12.34) from dual; -- 13 -12

floor(숫자) : 내림

  • 정수 반환
select floor(12.34), floor(-12.34) from dual; -- 12 -13

trunc(숫자, 자릿수) : 버림

  • 눈에 보이는 대로 숫자를 자름
select trunc(12.34), trunc(-12.34), trunc(-12.345,2), trunc(-12.343,2) from dual; -- 12	-12	-12.34	-12.34

mod(숫자, 나눌수) : 나머지 연산

select mod(7,2) from dual; -- 1

power(대상숫자, 제곱숫자) : 제곱

select power(3,2) from dual; -- 9

👨문자열 함수

upper(문자열) : 대문자로 변환


lower(문자열) : 소문자로 변환


initcap(문자열) : 첫 글자만 대문자로 변환


length(문자열) : 문자열의 길이


lengthb(문자열) : 문자열 byte 길이

  • 한글 1글자를 3byte로 인식
select dname, length(dname), lengthb(dname) from dept2; -- 사장실 3 9

substr(문자열, 시작[,개수]) : 부분 문자열

select substr('1234567890',3) from dual; -- 34567890
select substr('1234567890',3, 2) from dual; -- 34

instr(문자열, 찾을 문자열[,시작번지수]) : 문자열 찾은 후 인덱스 반환

  • 문자열에서 해당 문자의 위치를 찾아준다.
  • 시작 번지수가 -1(음수)이면 뒤에서부터 찾는다 .
  • 못 찾으면 0
select instr('abcd','b') from dual; -- 2 
select instr('absdboy','b', -1) from dual; -- 5 

replace(컬럼명, 찾을문자열, 변환문자열) : 문자열 찾은 후 문자열 교체

select replace(name, substr(name,2,1), '#') from student; -- 이름 가운데 글자 #으로 교체

lpad(문자열, 전체자리수, 특정문자) : 전체 자리수에서 나머지 왼쪽 공간을 특정문자로 채움

select lpad('abcd',7,'#') from dual; -- ###abcd

rpad(문자열, 전체자리수, 특정문자) : 전체 자리수에서 나머지 오른쪽 공간을 특정문자로 채움

select rpad('abcd',7,'#') from dual; -- abcd###

ltrim(문자열) : 왼쪽 공백 제거

select '  가나다라  ', ltrim(' 가나다라  '), length(ltrim(' 가나다라  ')) from dual; 
-- '  가나다라  ' '가나다라  '	6 

rtrim(문자열) : 오른쪽 공백 제거

select '  가나다라  ', rtrim(' 가나다라  '), length(rtrim(' 가나다라  ')) from dual; 
-- '  가나다라  ' '  가나다라' 6 

👴날짜 함수

sysdate : 현재 날짜


month_between(날짜, 날짜) : 두 날짜 사이의 개월 수

select months_between(to_date('12-20-2018', 'mm-dd-yyyy'),
					to_date('12-2-2017', 'mm-dd-yyyy')) months from dual; -- 12

add_months(날짜, 숫자) : 해당 날짜에서 숫자만큼 월을 더한 날짜

select next_day('2021/08/09',2) "다음주 월요일" from dual; -- 21/08/16 

next_day(날짜, 요일) :해당 날짜에서 다음 요일의 날짜

  • 1: 일요일, 2: 월요일, ..., 7: 토요일
select next_day('2021/08/09',2) "다음주 월요일" from dual; -- 21/08/16 

last_day(날짜) : 해당 날짜 달의 말일

select sysdate, last_day(sysdate) "last day", last_day(sysdate)- sysdate "말일까지 남은 날짜" from dual; 
-- 21/08/09	21/08/31 22

to_date(문자열) : 문자열을 날짜로 변환

select to_date('12-20-2018', 'mm-dd-yyyy') from dual; -- 18/12/20

to_char(날짜, 형식) : 날짜를 해당 날짜 형식으로 변환

select to_char(sysdate, 'yyyy-mm-dd hh:mi:ss') from dual; -- 2021-08-09 06:56:19

년/월/일 추출하기

extract(year from cast(컬럼명 as date))  --
extract(month from cast(컬럼명 as date)) --
extract(day from cast(컬럼명 as date)) --

시/분/초 추출하기

extract(hour from cast(컬럼명 as timestamp))  --
extract(minute from cast(컬럼명 as timestamp)) --
extract(second from cast(컬럼명 as timestamp)) --

👼선택문

조건을 주어, 조건에 따라 실행 문장을 다르게 할 때 사용하는 함수

decode

decode(대상,
           값, 문장,
           값, 문장,
           값, 문장,
           기타)
select deptno, decode(deptno, 101, '컴퓨터공학과', 
                                102, '멀티미디어공학과',
                                201, '전자공학과',
                                300, '인문사회학부',
                                '기타 학과') 학과
from department; 
select ename, decode(comm, null,'no commision', comm) from emp;

case

case when 조건1 then 문장
	 when 조건2 then 문장
	 when 조건3 then 문장
	 else 문장 
end
select deptno, case when deptno=101 then '컴퓨터공학과'
                    when deptno=102 then '멀티미디어공학과'
                    when deptno=201 then '전자공학과'
                    when deptno=300 then '인문사회학부'
                    else '기타 학과' 
                end 학과
from department;

🎅기타 함수

to_char(데이터) : 문자열로 변환

select ename, nvl(to_char(comm),'no commision') from emp;

cast(데이터 as 자료형) : 데이터의 자료형 변환

select ename, nvl(cast(comm as varchar2(20)),'no commision') from emp;
select ename, case when cast(comm as varchar2(20)) is null then 'no commision' 
				        else cast(comm as varchar2(20)) 
			  end comm 
from emp;

to_char(pay, 'L999,999,999') : 천단위구분기호

  • to_char(pay, 'L999,999,999') : 지역에 따른 화페표시
  • to_char(pay, '$999,999') : 달러 표시
select name, position, to_char(pay, 'L999,999,999') "급여(1000)"
from emp2 
where pay > (select min(pay) from emp2 where position = '과장');