[SQL]-(077) 서브 쿼리 사용하기7
[Reference] 초보자를 위한 SQL 200제
[SQL 문법]
서브 쿼리로 단일 값을 조회할 수 있다.
SELECT ename, sal, (select max(sal) from emp where job='SALESMAN') as MAXSAL,
(select min(sal) from emp where job='SALESMAN') as MINSAL
FROM emp
WHERE job='SALESMAN'
[예시]
# 오라클 연동 및 접속
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, sal, (select max(sal) from emp where job='SALESMAN') as MAXSAL,
(select min(sal) from emp where job='SALESMAN') as MINSAL
FROM emp
WHERE job='SALESMAN'
"""
)
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 SAL MAXSAL MINSAL
0 MARTIN 1250.0 1600 1250
1 ALLEN 1600.0 1600 1250
2 TURNER 1500.0 1600 1250
3 WARD 1250.0 1600 1250
Leave a comment