복잡한 조건의 데이터 SQL로 추출하기 예제1

이해하기 쉽고, 장황하지 않은 자료를 기반으로 강의를 진행합니다.
잔재미코딩 소식 공유
좀더 제약없이, IT 컨텐츠를 공유하고자, 자체 온라인 사이트와, 다음 두 채널도 오픈하였습니다
응원해주시면, 곧 좋은 컨텐츠를 만들어서 공유하겠습니다
●  잔재미코딩 뉴스레터 오픈 [구독해보기]
●  잔재미코딩 유투브 오픈 [구독해보기]

6. 복잡한 조건의 데이터 SQL로 추출하기 예제1

예제1: film테이블에서 2006년이나 2007년에 출시되었으면서, PG등급이거나, G등급의 영화제목을 모두 알려주세요

복잡한 문제는 무조건 최소로 작게 나누어 단계별로 해보는 연습을 해야 합니다.

참고 (등급)

G (general audiences): G ratings are most notable for what the films don’t include: sex and nudity, substance abuse, or realistic/non-cartoon violence.

PG (parental guidance): Some material may not be suitable for children. There may be mild strong language and some violence, but there will not be substance use or physical abuse.

PG-13 (parental guidance-13): Some material may not be suitable for children under 13. Any nudity has to be non-sexual and any swear words have to be used sparingly. Violence in PG-13 films may be intense, but must be bloodless.

R (restricted): No one under 17 admitted without an accompanying parent or guardian. This rating is given for strong and frequent language and violence, nudity for sexual purposes, and drug abuse.

NC-17 (no one under 17): This rare rating is given to films which feature mature elements in such profusion or intensity that it surpasses even the R.

Unrated: Typically reserved for previews of films not yet officially rated by the MPAA. A green title card indicates the preview is safe for all viewers, while red is for mature audiences.

문제 나누기1: 영화(film table)에 매겨진 등급(rating) 종류를 모두 출력하시요
In [47]:
SQL = "SELECT rating FROM film GROUP BY rating"
df = pd.read_sql(SQL, db)
df
Out[47]:
rating
0 G
1 PG
2 PG-13
3 R
4 NC-17
문제 나누기2: 영화(film table)에서 영화가 PG 또는 G 등급인 영화 수를 출력하세요
  • COUNT SQL 명령으로 WHERE 구문과 함께 써보기
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
In [52]:
SQL = """
SELECT rating, COUNT(*) FROM film WHERE rating = "PG" OR rating = "G" GROUP BY rating;
"""
df = pd.read_sql(SQL, db)
df
Out[52]:
rating COUNT(*)
0 G 178
1 PG 194
문제 나누기3: 영화(film table)에서 영화가 PG 또는 G 등급인 영화 제목을 출력하세요
  • SQL 명령으로 WHERE 구문과 함께 써보기
In [ ]:
SQL = """
SELECT rating, title FROM film WHERE rating = "PG" OR rating = "G";
"""
df = pd.read_sql(SQL, db)
df
문제 나누기4: 영화(film table)에서 영화가 PG 또는 G 등급이고, 2006년 또는 2007년에 만들어진 영화의 제목을 출력하세요
  • SQL 명령으로 WHERE 구문과 함께 써보기
In [ ]:
SQL = """
    SELECT rating, title 
    FROM film 
    WHERE 
        (rating = "PG" OR rating = "G") AND (release_year = 2006 OR release_year = 2007);
"""
df = pd.read_sql(SQL, db)
df