[Reference] 초보자를 위한 SQL 200제


[SQL 문법]

IF문을 SQL로 구현할 수 있다.
deptno가 10이면 300, 20이면 400, 그 외는 0으로 변환시켜준다.
맨 마지막은 if-else문에서 else에 해당하고 생략할 수 있다.

SELECT ename, deptno, DECODE(deptno,10,300,20,400,0) as Bonus
  FROM emp

[예시]

# 오라클 연동 및 접속
import pandas as pd
import cx_Oracle
dsn=cx_Oracle.makedsn('localhost',1521,'orcl')
db=cx_Oracle.connect('scott','tiger')
cursor=db.cursor()

# SQL 문법
cursor.execute("""
SELECT ename, deptno, DECODE(deptno,10,300,20,400,0) as Bonus
  FROM emp
""")

row=cursor.fetchall()
colname=cursor.description
col=[]

for i in colname:
    col.append(i[0])

# pandas를 사용한 데이터 프레임 형식으로 변환
emp=pd.DataFrame(row,columns=col)
print(emp)

[결과]

     ENAME  DEPTNO  BONUS
0     KING      10    300
1    BLAKE      30      0
2    CLARK      10    300
3    JONES      20    400
4   MARTIN      30      0
5    ALLEN      30      0
6   TURNER      30      0
7    JAMES      30      0
8     WARD      30      0
9     FORD      20    400
10   SMITH      20    400
11   SCOTT      20    400
12   ADAMS      20    400
13  MILLER      10    300

Leave a comment