mysql -h database-1.cuiypimjmxdl.us-east-2.rds.amazonaws.com -P 3306 -u admin -p
use zerobase;
select * from police_station;
select * from crime_status;
select count(column)
from tablename
where condition;
select count(*) from police_station;
select count(distinct police_station) from crime_station;
select distinct police_station from crime_station;
select count(distinct crime_type) from crime_status;
select distinct crime_type from crime_status;
select sum(column)
from tablename
where conditon;
select sum(case_number) from crime_status where status_type = '발생';
select sum(case_number) from crime_status where crime_type like '%살인%' and status_type = '발생';
select sum(case_number) from crime_status where police_station = '중부' and status_type = '검거';
select count(distinct name) from police_station;
select distinct name from police_station;
select count(distinct status_type) from crime_status;
select distinct status_type from crime_status;
select sum(case_number) from crime_status where police_station in ('종로', '남대문') and crime_type like '%강도%' and status_type = '발생';
select sum(case_number) from crime_status where crime_type like '%폭력%' and status_type = '검거';
select avg(column)
from tablename
where condition;
select avg(case_number) from crime_status where crime_type like '%폭력%' and status_type = '검거';
select police_station, crime_type, status_type, case_number from crime_status where crime_type like '%폭력%' and status_type = '검거';
select avg(case_number) from crime_status where police_station = '중부' and status_type = '발생';
select police_station,crime_type, status_type, case_number from crime_status where police_station = '중부' and status_type = '발생';
select min(column)
from table
where condition;
select min(case_number) from crime_status
where crime_type like '%강도%' and status_type ='발생';
select police_station, crime_type, case_number
from crime_status
where crime_type like '%강도%' and status_type ='발생';
select min(case_number) from crime_status where police_station = '중부' and status_type ='검거';
select police_station, crime_type, case_number from crime_status where police_station ='중부' and status_type =' 검거';
select max(column)
from tablename
where condition;
select max(case_number)
from crime_status
where crime_type like '%살인%' and status_type ='검거';
select * from crime_status
where crime_type like '%살인%' and status_type ='검거';
select max(case_number) from crime_status where police_station = '강남' and status_type ='발생';
select * from crime_status where police_station = '강남' and status_type ='발생';
select avg(case_number)
from crime_status
where crime_type like '%살인%' and status_type = '발생';
select * from crime_status
where crime_type like '%살인%' and status_type = '발생';
select avg(case_number), crime_type
from crime_status
where police_station ='서초' and status_type = '검거';
select police_station, case_number, crime_type, status_type
from crime_status
where police_station ='서초' and status_type = '검거';
select avg(case_number)
from crime_status
where police_station in ('구로','도봉')
and crime_type = '살인' and status_type ='검거';
select * from crime_status
where police_station in ('구로','도봉')
and crime_type = '살인' and status_type ='검거';
select min(case_number) from crime_status
where police_station = '광진' and status_type ='검거';
select * from crime_status
where police_station = '광진' and status_type ='검거';
select min(case_number)
from crime_status
where police_station = '성북' and status_type = '발생';
select * from crime_status
where police_station = '성북' and status_type = '발생';
select max(case_number)
from crime_status
where police_station = '영등포' and status_type = '발생';
select * from crime_status
where police_station = '영등포' and status_type = '발생';
select max(case_number) from crime_status
where crime_type like '%절도%' and status_type = '검거';
select * from crime_status
where crime_type like '%절도%' and status_type = '검거';
select column1, column2, ...
from table
where condition
group by column1, column2, ...
order by column1, column2, ...
select police_station
from crime_status
group by police_station
order by police_station;
select police_station, sum(case_number) as '발생건수'
from crime_status
where status_type ='발생'
group by police_station order by 발생건수 desc;
select police_station, avg(case_number) as 평균검거건수
from crime_status
where status_type='검거'
group by police_station
order by 평균검거건수 desc;
select police_station, status_type, avg(case_number)
from crime_status
group by police_station, status_type ;
select column1, column2, ...
from table
where condition
group by column1, column2, ...
having condition (Aggregate Functions)
order by column1, column2, ...
select police_station, sum(case_number) as 'count'
from crime_status
where status_type='발생'
group by police_station
having count > 4000;
select police_station, avg(case_number)
from crime_status
where (crime_type like '%폭력%' or crime_type like '절도') and status_type ='발생'
group by police_station
having avg(case_number) >= 2000;
select police_station, avg(case_number)
from crime_status
where crime_type like '%절도%' and status_type ='발생'
group by police_station
order by avg(case_number) desc limit 10;
select avg(case_number)
from crime_status
where police_station like '%송파%' and crime_type like '%절도%' and status_type ='발생';
select police_station, max(case_number)
from crime_status
where status_type ='검거'
group by police_station
order by max(case_number) asc limit 5;
select max(case_number)
from crime_status
where status_type ='검거' and police_station like '방배';
select police_station, min(case_number)
from crime_status
where status_type = '검거'
group by police_station having min(case_number)
order by min(case_number) desc ;
select min(case_number)
from crime_status
where status_type = '검거' and police_station like '중랑';
select police_station, avg(case_number)
from crime_status
where police_station like '%대문' and status_type ='발 생'
group by police_station
having avg(case_number) > 500;
select police_station, avg(case_number)
from crime_status
where police_station like '서대문' and status_type ='발생';
mysql -h database-1.cuiypimjmxdl.us-east-2.rds.amazonaws.com -P 3306 -u admin -p
use zerobase;
vscode - sandwich 테이블 생성
import mysql.connector
import pandas as pd
conn = mysql.connector.connect(
host = 'database-1.cuiypimjmxdl.us-east-2.rds.amazonaws.com',
port = 3306,
user = 'zero',
password = '<password>', 데이터베이스와 동일
database = 'zerobase'
)
df = pd.read_csv('03. best_sandwiches_list_chicago2.csv', encoding='utf-8')
df['Price'] = df['Price'].str.replace('$','')
df['Price'] = df['Price'].astype('float')
df.info()
sql = 'create table sandwich (ranking int, cafe varchar(32), menu varchar(32), address varchar(32), price float)'
cursor = conn.cursor(buffered=True)
cursor.execute(sql)
sql = 'insert into sandwich values (%s, %s, %s, %s, %s)'
for i, row in df.iterrows():
cursor.execute(sql, tuple(row))
print(tuple(row))
conn.commit()
conn.close()
select ucase(string);
select ucase('This Is ucase Test.');
select ucase(menu) from sandwich where price > 15;
select lcase(string);
select lcase('This Is ucase Test.');
select lcase(menu) from sandwich where price < 5;
select mid(string, start_position, length);
select mid('This is mid test', 1, 4);
select mid('This is mid test', 6, 5);
select mid('This is mid test', -4, 4);
select mid('This is mid test', -8, 3);
select mid(cafe, 6, 4) from sandwich where ranking = 11;
select length(string);
select length('This is len test');
select length('');
select length(' ');
select length(null);
select length(address), address from sandwich where ranking <= 3;
select round(number, decimals_place);
select round(315.625);
select round(315.625,0);
select round(315.625,1);
select round(315.625,2);
select round(315.625,-1);
select round(315.625,-2);
select ranking, round(price,0), price
from sandwich order by ranking desc limit 3;
select now();
select now();
format : 숫자를 천단위 콤마가 있는 형식으로 반환하는 함수
- number : 포맷을 적용할 문자 혹은 숫자
- decimals : 표시할 소수점 위치
예제1 (format) 소수점을 표시하지 않을 경우 0
select format(12345.6789, 0);
select format(12345.6789,2);
localmysql에 있음
select format(가격,0) from oil_price where round(가격, -3) >=2000
select ucase(cafe), lcase(menu) from sandwich;
select ranking,cafe, mid(menu, -3, 3)
from sandwich where ranking = 10;
select menu, avg (length(menu)) from sandwich;
localmysql에 있음
select 가격, round(가격, -2) from oil_price;
localmysql에 있음
select 가격,format(가격, 0) from oil_price where round(가격,-2) >= 2000;
하나의 SQL문 안에 포함되어 있는 또 다른 SQL문을 말한다
메인쿼리가 서브쿼리를 포함하는 종속적인 관계이다
- 서브쿼리는 메인쿼리의 컬럼 사용 가능
- 메인쿼리는 서브쿼리의 컬럼 사용 불가
Subquery는 괄호를 묶어서 사용
단일 행 혹은 복수 행 비교 연산자와 함께 사용 가능
subquery에서는 order by를 사용 X
스칼라 서브쿼리(Scalar Subquery) - SELECT절에 사용
인라인 뷰(Inline View) - FROM절에 사용
중첩 서브쿼리(Nested Subquery) - WHERE 절에 사용
select column1, (select column2 from table2 where condition)
from table1
where condition;
select
case_number,
(select avg(case_number) from crime_status where crime_type like '%강도%' and status_type = '검거') as avg
from crime_status
where police_station = '은평' and crime_type like '%강도%' and status_type = '검거';
select a.column, b.column
from table1 a, (select column1, column2 from table2) b
where condition;
select c.police_station, c.crime_type, c.case_number
from crime_status as c,
( select police_station, max(case_number) as count
from crime_status
where status_type ='발생' group by police_station) as m
where c.police_station = m.police_station and c.case_number = m.count;
select column_names
from table_name
where column_name = (select column_name from table_name where condition)
order by column_name;
celect name
from celeb where name = select host from snl_show;
select name
from celeb
where name = (select host from snl_show where id=1);
select column_names
from table_name
where column_name in (select column_name from table_name where condition)
order by column_names;
select host
from snl_show
where host in (select name
from celeb
where job_title like '%영화배우%');
select column_names
from table_name
where exists (select column_name from table_name where condition)
order by column_names;
select name
from police_station as p
where exists (select police_station
from crime_status c
where p.name = c.reference and case_number > 2000);
select column_names
from table_name
where column_name = any (select column_name from table_name where condition)
order by column_names;
select name
from celeb
where name = any(select host from snl_show);
select column_names
from table_name
where column_name = all (select column_name from table_name where condition)
order by column_names;
select name
from celeb
where name = all (select host from snl_show where id = 1);
select column_names
from tablename a
where (a.column1, a.column2, ...) in (select b.column1, b.column2, ... from tablename b where a.column_name = b.column_name)
order by column_names;
select name, sex, agency
from celeb
where (sex, agency) = (select sex, agency from celeb where name = '강동원');
select max(가격), (select avg(가격) from oil_price where 셀프 = 'Y') as avg
from oil_price
where 상표 ='SK에너지';
select o.가격, o.상호, o.상표
from oil_price as o , (select 상표, max(가격) as max from oil_price group by 상표) as m
where o.상표 = m.상표 and o.가격 = m.max;
select 상호, 가격
from oil_price where 가격 > (select avg(가격) from oil_price);
💻 출처 : 제로베이스 데이터 취업 스쿨