AI School 8기 (LIKELION, 22.12~23.05)

[AI School-TIL] SQL(BigQuery) 1일차_23.01.13

data_start_ 2024. 12. 11. 12:08

SQL문 - 구글 빅쿼리를 이용해서 실습하기.
축약한 데이터, 집계 데이터를 그때그때 테이블로 만들 수 있다.

실행 단축키
윈도우 : control + 엔터
맥 : command + 엔터

' ; '로 문장이 끝났음을 표시
SQL 작성 시, 대문자로 하는 게 관행이나, 결과가 나오는 데 크게 관계가 없다.
보통은 테이블명만 입력하는 게 관행임.

select

: 데이터를 조회하는 명령어
/ 간단한 산술 연산자 ( +, -, *, / )도 쿼리 결과로 나옴
/ 문자열도 나옴( + 연산자는 안 됨 -> 함수를 사용해야 함)
: from 뒤에 어디 테이블에서 가져오는지 먼저 작성하는 게 좋다.

# 1) 어디서?
select first_name, last_name  
from `thelook_ecommerce.users`;

# 전체 테이블 조회

select * from `thelook_ecommerce.users`;

# 연습문제 1-1

# 회원(users) 테이블의 모든 데이터를 조회하세요.

select * from `thelook_ecommerce.users`;

# 연습문제 1-2

# 상품정보(products) 테이블의 모든 데이터를 조회하세요.

select * from `thelook_ecommerce.products`;

# SQL 연습문제 1-3

# 주문정보(orders) 테이블의 모든 데이터를 조회하세요.

select * from `thelook_ecommerce.orders`;

# SQL 연습문제 1-4

# 회원(users) 테이블의 이메일(email) 정보를 조회하세요.

select email from `thelook_ecommerce.users`;

# SQL 연습문제 1-5

# 회원(users) 테이블의 이름(first\_name), 성(last\_name), 이메일(email), 국가 정보(country)를 조회하세요.

select first_name, last_name, email, country  
from `thelook_ecommerce.users`;

# SQL 연습문제 1-6

# 상품정보(products) 테이블의 id, 카테고리(category), 이름(name), 판매가격(retail\_price), 비용(cost)을 조회하세요.

select id, category, name, retail_price, cost  
from `thelook_ecommerce.products`;

# SQL 연습문제 1-7

# 상품정보(products) 테이블의 id, 카테고리(category), 이름(name), 판매가격(retail\_price), 비용(cost), 판매이익(판매가격 - 비용)을 조회하세요.

select id,  
category,  
name,  
retail_price,  
cost,  
retail_price-cost  
from `thelook_ecommerce.products`

# SQL 연습문제 1-8

# 회원(users) 테이블의 이름(first\_name), 나이(age), 출생연도(나이 데이터로 계산, 만 나이로 기준 ) 데이터를 조회해보세요.

select first_name,  
age,  
2023 - age + 1  
from `thelook_ecommerce.users`  

//
select first_name from thelook_ecommerce.users (O)
=> 일반적으로 이렇게 사용합니다.
select first_name from thelook_ecommerce.users (O)
select first_name from thelook_ecommerce.users (O)
=> 백틱이 다 끝날 때까지 구문을 끝내지 않고 문자열로 쓰지 않는 것처럼(맨 위 구문처럼) 처리합니다.
그렇기에 실행이 됩니다.
=> 아래 2가지 사항은 안됩니다. 이유는 table을 문자열로 처리하지 않습니다.
select first_name from 'thelook_ecommerce'.'users' (X)
select first_name from 'thelook_ecommerce.users' (X)
//

as

# 필드명 별칭 붙이기

select  
id as product\_id,  
category as product\_category,  
name as product\_name,  
retail\_price as product\_retail\_price,  
cost as product\_cost,  
retail\_price-cost as product\_profit  
from `thelook_ecommerce.products`;

# 테이블명 별칭 붙이기

select  
a.id,  
a.name  
from `thelook_ecommerce.products` as a;

# 보통 축약할 때는, 모음을 빼고 자음으로 products -> prd

# 더 복잡해지면 a,b,c나 t1, t2, t3와 같은 방식으로 축약

limit

# 최근 10개만 가지고 올때, limit를 사용

select *  
from `thelook_ecommerce.products`  
limit 10;

# SQL 연습문제 2-1

# 상품정보(products) 테이블에서 5개 레코드만 조회하세요.

select distinct *  
from `thelook_ecommerce.products`  
limit 5;

# SQL 연습문제 2-2

#회원(users) 테이블에서 이메일 주소(email) 20개를 조회하세요.  
select distinct email  
from `thelook_ecommerce.users`  
limit 20;  

distinct

# 중복 제거해서, 필드명 고유값만 출력하기

select distinct category  
from `thelook_ecommerce.products`;

# country, city를 세트로 묶어서 중복 제거

select distinct country, city  
from `thelook_ecommerce.users`;

# SQL 연습문제 2-3

#주문정보(orders) 테이블에서 상태정보(status)를 중복제거하여 아래와 같이 결과가 나오도록 조회하세요.  
select distinct status  
from `thelook_ecommerce.orders`;

# SQL 연습문제 2-4

# 상품정보(products) 테이블에서 카테고리(category)를 중복제거하여 아래와 같이 조회하세요.

select distinct category  
from `thelook_ecommerce.products`;

# SQL 연습문제 2-5

# 상품정보(products) 테이블에서 카테고리(category), 브랜드(brand)를 중복제거하여 30개 조회하세요.

# 각 결과 컬럼의 이름은 다음과 같이 지정하세요.

# \- 카테고리 → product\_category

# \- 브랜드 → product\_brand

select  
distinct category as product\_category,  
brand as product\_brand  
from `thelook_ecommerce.products`  
limit 30;

# SQL 연습문제 2-6

# 상품정보(products) 테이블에서 id, 카테고리(category), 이름(name), 판매가격(retail\_price), 비용(cost), 판매이익(판매가격 - 비용), 수익율을 조회하세요.

# 비용 1000원, 판매가 1200원 일 경우

# 수익율은 (1,200-1,000)/1,000\*100 = 20% 입니다.

# 수익율 : (판매가 - 비용) / 비용 x 100

# 각 컬럼의 이름은 다음과 같이 표현합니다.

# \- id → product\_id

# \- 카테고리 → product\_category

# \- 상품명 → product\_name

# \- 판매가격 → product\_price

# \- 비용 → product\_cost

# \- 판매이익 → product\_profit

# \- 수익율 → product\_profit\_rate

select id as product\_id,  
category as product\_category,  
name as product\_name,  
retail\_price as product\_price,  
cost as product\_cost,  
retail\_price - cost as product\_profit,  
(retail\_price - cost)/ cost \* 100 as product\_profit\_rate  
from `thelook_ecommerce.products`;  

where (필터 기능)

비교 연산자

<
!=
<>

select *  
from `thelook_ecommerce.users`  
where id = 2427;

select *  
from `thelook_ecommerce.users`  
where age <= 50  
or age >= 60;

select *  
from `thelook_ecommerce.users`  
where (country = 'Japan' or country = 'Brasil') #괄호 안에 있는 연산부터 먼저 적용  
and age >= 60;  

논리 연산자 (sql은 집합 연산)
true : 1
false : 0

and : 곱하기, 교집합
or : 더하기, 합집합
not : 반대로 뒤집음

select true and true  
select true and false

between ㅁ and o

select *  
from `thelook_ecommerce.users`  
where created\_at between '2021-01-01' and '2021-01-05';

select *  
from `thelook_ecommerce.users`  
where age between 20 and 30;

select *  
from `thelook_ecommerce.users`  
where age >= 20  
and age <= 30;  

in

select * from `thelook_ecommerce.users`  
where country = 'United States'  
or country = 'Brasil'  
or country = 'Korea'  
or country = 'Japan';

select * from `thelook_ecommerce.users`  
where country in ('United States', 'Brasil', 'Korea', 'Japan');  

like와 와일드카드(%)

%ㅁ
ㅁ%
%ㅁ%
ㅁ___ (ㅁ으로 시작하는 글자수)

select *  
from `thelook_ecommerce.users`  
where first\_name like 'M%';

select *  
from `thelook_ecommerce.users`  
where first\_name like '%a';

select *  
from `thelook_ecommerce.users`  
where first\_name like '%gi%';

select distinct first\_name  
from `thelook_ecommerce.users`  
where first\_name like 'Da__';  

NULL

is null
is not null

# SQL 연습문제 3-1

# 상품정보(products) 테이블에서 카테고리(category)가 ‘Swim’ 인 레코드의 모든 항목를 조회하세요.

select \*  
from `thelook_ecommerce.products`  
where category = 'Swim';

# 어디서 from

# 무엇을 select

# 어떤 것을 where

# SQL 연습문제 3-2

# 상품정보(products) 테이블에서 브랜드(brand)가 ‘2EROS’인 레코드의 id, 비용(cost), 브랜드(brand)를 조회하세요.

select id, cost, brand  
from `thelook_ecommerce.products`  
where brand = '2EROS';

# SQL 연습문제 3-3

# 상품정보(products) 테이블에서 비용(cost)이 30이하이고 성별(department)이 ‘Men’인 모든 레코드를 10개를 조회하세요.

select \*  
from `thelook_ecommerce.products`  
where cost <= 30  
and department = 'Men'  
limit 10; #limit는 제일 끝

# SQL 연습문제 3-4

# 상품정보(products) 테이블에서 판매가격(retail\_price)이 40이상인 레코드들의 카테고리(category) 속성값을 중복제거(distinct)하여 조회하세요.

select distinct category  
from `thelook_ecommerce.products`  
where retail\_price >= 40;

# SQL 연습문제 3-5

# 상품정보(products) 테이블에서 비용(cost)이 50이상 70이하인 모든 레코드들 조회하세요.

select \*  
from `thelook_ecommerce.products`  
where cost >= 50 and cost <= 70;

select \*  
from `thelook_ecommerce.products`  
where cost between 50 and 70;

# SQL 연습문제 3-6

# 상품정보(products) 테이블에서 상품명(name)에 ‘Men’과 ‘Sport’ 두 단어가 들어간 모든 레코드들 조회하세요.

select \*  
from `thelook_ecommerce.products`  
where name like '%Men%'  
and name like '%Sport%';  

도전문제

# SQL 연습문제 3-7

#상품정보(products) 테이블에서  
#브랜드(brand)가 ‘TYR’이 아니고  
#이름(name)에 ‘Suit’가 포함되고  
#할인율이 50이상인  
#모든 레코드와 할인율을 조회합니다.

select \*,  
cost / retail\_price \* 100 as sale\_price  
from `thelook_ecommerce.products`  
where brand != 'TYR'  
and name like '%Suit%'  
and cost/retail\_price \* 100 >= 50;  

프로그래머스 문제

https://school.programmers.co.kr/learn/courses/30/lessons/59046

# 동물 보호소에 들어온 동물 중 ---> from

# 이름이 Lucy, Ella, Pickle, Rogan, Sabrina, Mitty인 --> 조건

# 동물의 아이디와 이름, 성별 및 중성화 여부를 조회하는 -> select

# SQL 문을 작성해주세요.

# 이때 결과는 아이디 순으로 조회해주세요 --> 정렬순서

select ANIMAL\_ID,  
NAME,  
SEX\_UPON\_INTAKE  
from ANIMAL\_INS  
where NAME in ('Lucy', 'Ella', 'Pickle', 'Rogan', 'Sabrina', 'Mitty')  
order by ANIMAL\_ID  

[데이터 집계함수]

count

select count(id)  
from `thelook_ecommerce.users`;

# 중복값 제거 후, 데이터 집계

select count(distinct city)  
from `thelook_ecommerce.users`;

sum

select sum(retail\_price)  
from `thelook_ecommerce.products`;  

min, max

select min(cost), max(retail_price)  
from `thelook_ecommerce.products`;  

avg

  • 평균

    variance, stddev

  • 분산, 표준편차

group by

  • 쪼갠 기준이 되는 필드명을 앞에 써준다.
    select gender, count(id) as user_count  
    from `thelook_ecommerce.users`  
    group by gender;  

[연습문제]

# SQL 연습문제 4-1

# 회원(users) 테이블에서 전체 유저의 평균연령을 조회하세요.

select avg(age)  
from `thelook_ecommerce.users`;

# SQL 연습문제 4-2

회원(users) 테이블에서 여성 유저의 평균연령을 조회하세요.  
select avg(age)  
from `thelook_ecommerce.users`  
where gender = 'F';