이번 포스팅에서는 SQL의 기본 개념을 간단하게 살펴보고, DataCamp에서 제공한 students
데이터셋을 이용해 체류 기간(stay)이 국제 학생(Inter)의 정신 건강 점수에 어떤 영향을 미치는지 분석해봅니다.
SQL은 데이터베이스(DB)와 대화하는 언어입니다.
관계형 데이터베이스(RDBMS)에서 데이터를:
할 때 사용됩니다.
SQL은 데이터 분석뿐만 아니라, 실제 기업에서도 가장 널리 사용되는 데이터 처리 언어입니다.
분석에 사용할 students
테이블은 국제 학생과 국내 학생의 정신 건강 지표를 담고 있습니다.
Field Name | Description |
---|---|
inter_dom | 학생 유형 (국제학생 Inter / 국내학생 Dom) |
japanese_cate | 일본어 숙련도 |
english_cate | 영어 숙련도 |
academic | 학위 수준 (학부/대학원) |
age | 나이 |
stay | 체류 기간(년) |
todep | 우울 점수 (PHQ-9) |
tosc | 사회적 연결감 점수 (SCS) |
toas | 문화적 스트레스 점수 (ASISS) |
먼저, 테이블 구조와 일부 데이터를 확인합니다.
SELECT *
FROM students;
🔹 이 쿼리는 모든 컬럼과 행을 보여줍니다.
실전에서는 필요한 컬럼만 조회하는 것이 더 효율적입니다.
문제에서 요구하는 분석은 다음과 같습니다:
inter_dom = 'Inter'
)만 분석stay
)별로 그룹화SELECT
stay,
COUNT(*) AS count_int,
ROUND(AVG(todep), 2) AS average_phq,
ROUND(AVG(tosc), 2) AS average_scs,
ROUND(AVG(toas), 2) AS average_as
FROM students
WHERE inter_dom = 'Inter' -- 국제 학생만 필터링
GROUP BY stay
ORDER BY stay DESC; -- 체류 기간 내림차순 정렬
COUNT(*) AS count_int
→ 체류 기간별 학생 수 집계ROUND(AVG(todep), 2)
→ PHQ-9 평균 (소수점 둘째 자리)ROUND(AVG(tosc), 2)
→ SCS 평균ROUND(AVG(toas), 2)
→ ASISS 평균WHERE inter_dom = 'Inter'
→ 국제 학생만 선택GROUP BY stay
→ 체류 기간별 그룹화ORDER BY stay DESC
→ 체류 기간이 긴 순으로 정렬stay | count_int | average_phq | average_scs | average_as |
---|---|---|---|---|
10 | 12 | 5.50 | 42.30 | 33.10 |
9 | 8 | 6.10 | 40.20 | 34.00 |
... | ... | ... | ... | ... |
✔️ 결과는 약 9개의 행과 5개의 열을 반환합니다.
SQL 없이도 Pandas를 이용하면 CSV 파일에서 같은 분석을 할 수 있습니다.
다음 코드를 Colab 또는 로컬에서 실행해보세요.
import pandas as pd
# CSV 파일 로드
df = pd.read_csv("datalab_export_2025-08-03 13_33_54.csv")
# 국제 학생만 필터링
df_inter = df[df['inter_dom'] == 'Inter']
# 그룹화 및 집계
result = (
df_inter
.groupby('stay')
.agg(
count_int=('stay', 'count'),
average_phq=('todep', lambda x: round(x.mean(), 2)),
average_scs=('tosc', lambda x: round(x.mean(), 2)),
average_as=('toas', lambda x: round(x.mean(), 2)),
)
.reset_index()
.sort_values('stay', ascending=False)
)
# 결과 확인
import ace_tools as tools
tools.display_dataframe_to_user(name="Stay vs Mental Health Scores", dataframe=result)
🐼 Pandas는 서버 없이도 손쉽게 데이터 분석을 할 수 있습니다.
PostgreSQL 서버가 있다면 psycopg2
라이브러리로 동일한 SQL을 실행할 수 있습니다.
import psycopg2
import pandas as pd
# PostgreSQL 연결 설정
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host",
port="5432"
)
# SQL 쿼리
query = """
SELECT
stay,
COUNT(*) AS count_int,
ROUND(AVG(todep), 2) AS average_phq,
ROUND(AVG(tosc), 2) AS average_scs,
ROUND(AVG(toas), 2) AS average_as
FROM students
WHERE inter_dom = 'Inter'
GROUP BY stay
ORDER BY stay DESC;
"""
# 결과를 Pandas DataFrame으로 불러오기
df_sql = pd.read_sql(query, conn)
# 연결 종료
conn.close()
# 결과 확인
tools.display_dataframe_to_user(name="SQL Query Result from PostgreSQL", dataframe=df_sql)
🐘 psycopg2는 실제 DB 서버에서 SQL을 실행할 때 사용됩니다.
방법 | 장점 | 단점 |
---|---|---|
Pandas | 서버 없이 CSV만으로도 분석 가능 | 대용량 데이터 처리 시 느림 |
psycopg2 | 실전 환경과 동일, DB 직접 쿼리 가능 | PostgreSQL 서버 필요 |
이번 포스팅에서 배운 것:
SQL은 데이터 분석의 기본이자 강력한 도구입니다.
이 예제를 통해 데이터 필터링, 그룹화, 집계를 쉽게 연습할 수 있었습니다.