EX)
SELECT CustomerId
FROM invoice
WHERE Total <= (SELECT AVG(Total)
FROM invoice);
# 서브쿼리가 변수처럼 활용된 경우
SELECT *
FROM (
SELECT CustomerId
FROM customer
WHERE CustomerId < 10
);
# 서브쿼리가 테이블 처럼 활용된 경우
SELECT customer.LastName,
(SELECT COUNT( * )
FROM invoice
WHERE customer.CustomerId = invoice.CustomerId)
AS Invoi ceCount
FROM customer;
# 서브쿼리가 컬럼처럼 활용된 경우
SELECT *
FROM tracks
WHERE Milliseconds > (SELECT AVG(Milliseconds) from tracks)
2. albums 테이블과 tracks 테이블을 사용하여 각 앨범의 제목과 해당 앨범의 곡 수를 함께 선택
SELECT count(tracks.TrackId),
(select albums.Title from albums WHERE albums.AlbumId =tracks.AlbumId)
FROM tracks
SELECT a.title,(select count(t.TrackId) from tracks t where t.AlbumId=a.AlbumId)
from albums a
! pip install pysqlite3
import sqlite3
conn = sqlite3.connect("./chinook.db")
conn
c=conn.cursor()
query=''' SELECT *
FROM albums
'''
c.execute(query)
c.fetchall() #테이블 다 불러오기
c.fetchone() #테이블 한 줄씩 불러오기
c.close()
conn.close()
import sqlite3
import pandas as pd
conn = sqlite3.connect("./chinook.db")
c=conn.cursor()
query=''' SELECT *
FROM albums
'''
df=pd.read_sql(query,conn)
df.head()
! pip install psycopg2
! pip install sqlalchemy
import psycopg2
db_params ={
"host":"localhost",
"database":"postgres",
"user":"postgres",
"password":"0000",
"port":"5432"
}
try:
conn = psycopg2.connect(**db_params)
cursor=conn.cursor()
create_table_query="CREATE TABLE IF NOT EXISTS example_table(id SERIAL PRIMARY KEY, data VARCHAR)"
insert_data_query="INSERT INTO example_table (data) VALUES('HI')"
cursor.execute(create_table_query)
cursor.execute(insert_data_query)
conn.commit()
query=''' SELECT *
FROM example_table
'''
cursor.execute(query)
print(cursor.fetchall())
print("테이블 생성 완료")
except(Exception, psycopg2.Error) as error:
print(error)
finally:
if conn:
conn.close()
print("데이터베이스 연결 종료")
import psycopg2
db_params ={
"host":"snuffleupagus.db.elephantsql.com",
"database":"dxamdbqz",
"user":"dxamdbqz",
"password":"se4C9znG6e_gfsRY5JVX8Wq6RAUylSVK",
"port":"5432"
}
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/jin0choi1216/dataset/main/AAPL.csv')
df.head(3)
import psycopg2
from sqlalchemy import create_engine
db_params ={
"host":"snuffleupagus.db.elephantsql.com",
"database":"dxamdbqz",
"user":"dxamdbqz",
"password":"se4C9znG6e_gfsRY5JVX8Wq6RAUylSVK",
"port":"5432"
}
try:
conn = psycopg2.connect(**db_params)
cursor=conn.cursor()
engine=create_engine('postgresql://dxamdbqz:se4C9znG6e_gfsRY5JVX8Wq6RAUylSVK@snuffleupagus.db.elephantsql.com/dxamdbqz')
with engine.connect() as con:
df.to_sql('aapl', con, if_exists='replace')
print("테이블 생성 완료")
except(Exception, psycopg2.Error) as error:
print(error)
finally:
if conn:
conn.close()
print("데이터베이스 연결 종료")
import psycopg2
from sqlalchemy import create_engine
db_params ={
"host":"snuffleupagus.db.elephantsql.com",
"database":"dxamdbqz",
"user":"dxamdbqz",
"password":"se4C9znG6e_gfsRY5JVX8Wq6RAUylSVK",
"port":"5432"
}
try:
conn = psycopg2.connect(**db_params)
cursor=conn.cursor()
engine=create_engine('postgresql://dxamdbqz:se4C9znG6e_gfsRY5JVX8Wq6RAUylSVK@snuffleupagus.db.elephantsql.com/dxamdbqz')
with engine.connect() as con:
aapl=pd.read_sql('SELECT * FROM aapl', con)
print("테이블 생성 완료")
except(Exception, psycopg2.Error) as error:
print(error)
finally:
if conn:
conn.close()
print("데이터베이스 연결 종료")
aapl.head()