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


[SQL 문법]

여러 개의 쿼리 결과 데이터를 위아래로 하나의 결과로 출력할 수 있다.
UNION ALL과 비교하여 UNION 연산자는 중복된 데이터를 하나의 고유한 값으로 출력하고, 내림차순 정렬한다.

SELECT deptno, sum(sal)
  FROM emp
  GROUP BY deptno
UNION
SELECT null as deptno, sum(sal)
  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 deptno, sum(sal)
  FROM emp
  GROUP BY deptno
UNION
SELECT null as deptno, sum(sal)
  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)

[결과]

   DEPTNO  SUM(SAL)
0    10.0      8750
1    20.0     10875
2    30.0      9400
3     NaN     29025

Leave a comment