[SQL]-(046) 데이터분석 함수로 바로 전 행과 다음 행 출력하기
[Reference] 초보자를 위한 SQL 200제
[SQL 문법]
데이터의 바로 전 행과 바로 다음 행을 출력할 수 있다.
cursor.execute("""
SELECT empno, ename, sal,
LAG(sal,1) over (order by sal asc) "Pre Rows",
LEAD(sal,1) over (order by sal asc) "Next Rows"
FROM emp
WHERE job in ('ANALYST', 'MANAGER')
[예시]
# 오라클 연동 및 접속
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 empno, ename, sal,
LAG(sal,1) over (order by sal asc) "Pre Rows",
LEAD(sal,1) over (order by sal asc) "Next Rows"
FROM emp
WHERE job in ('ANALYST', 'MANAGER')
""")
row=cursor.fetchall()
colname=cursor.description
col=[]
for i in colname:
col.append(i[0])
# pandas를 사용한 데이터 프레임 형식으로 변환
emp=pd.DataFrame(row,columns=col)
print(emp)
[결과]
EMPNO ENAME SAL Pre Rows Next Rows
0 7782 CLARK 2450.0 NaN 2850.0
1 7698 BLAKE 2850.0 2450.0 2975.0
2 7566 JONES 2975.0 2850.0 3000.0
3 7902 FORD 3000.0 2975.0 3000.0
4 7788 SCOTT 3000.0 3000.0 NaN
Leave a comment