3. MY SQL 실습 해보기
데이터는 타이타닉의 승객 정보이다 .
여기서 SQL실습을 진행을 해보았다 ....
use playdata; ---------- 데이터 파일을 불러오기
select database(); ------- 데이터베이스를 조회하라는 의미 !
show tables; -----테이블을 조회한다는 말
select* from titanic_raw; ----------잘 불러왔는지 확인
/*
passengerid -승객 (pk)
survied - 생존여부(0:사망, 1:생존)
pclass - 객실 등급 (1 , 2 , 3 )
name -이름
gender - 성별
sibsp - 동반한 형제 또는 자매 또는 배우자수
parch - 동반한 부모 또는 자식의 수
ticket - 티켓번호
fare - 요금
cabin - 객실 번호
embarked - 탑승한 항구(C:프랑스항구 Q: 아일랜드항구, S:영국 항구)
*/
-- select : 조회하겠다는 의미
select name, age from titanic_raw; ---- 승객 이름과 나이만 조회하겠다는 말
select name as "이름", age as "나이" from titanic_raw; ----컬럼명을 바꿀수 있다 . 컬럼명 뒤에 as를 쓴 다음 바꿀 이름을 지정.
select * ------여기 별표시는 테이블 전체를 확인하겠다는 의미
from titanic_raw
where survived =1; ----- where를 쓰면 조건식을 쓸수가 있다 .
그래서 이 코드를 해석하면 생존자의 모든 정보를 조회한다이다.
select*
from titanic_raw
where age > 59; ---- 비교연산자도 가능 !
-- is null : 있거나 없거나 ! 파이썬의 bool연산자와 비슷
select *
from titanic_raw
where age is null; ---- age가 null 인 것을 조회하겠다 라는 의미 !
select *
from titanic_raw
where age is not null; ----- 반대로 null이 아닌 것을 조회하겠다 라는 의미
-- like :특정 문자열을 찾고 싶을 때 사용 !
select *
from titanic_raw
where name like '%miss%'; ------ 컬럼 명 앞에 like를 써주고 "%문자열%" 이렇게 쓰면 된다
select*
from titanic_raw
where name like'%miss%'or name like'%mrs%'; ---------만약에 1개이상으로 찾고싶을때면 or연산자를 써서 like를 두개 쓴다
-- and, or
select *
from titanic_raw
where survived = 1 and gender ='female'; 조건을 두개 주고 싶을때 사용 !
select*
from titanic_raw
where name like "%mrs%" or name like "%miss%";
-- in, not in : 포함 시키고싶을때 , 아님 포함 안 시키고싶을때!
select*
from titanic_raw
where embarked not in ("C","S"); ------ embark 라는 테이블에서 특정한 컬럼을 포함 안시킬때 사용
-- between: 구간 조회
select*
from titanic_raw
where age between 20 and 40; ----- 특정 구간을 설정하고 싶을때 사용 !
select*
from titanic_raw
where parch between 1 and 2;
select*
from titanic_raw
where cabin between "A01" and "B22"; -------
알파벳도 가능하다 ! 알파벳이랑 숫자가 같이 쓰이면 알파벳이 먼저 있으니 알파벳순서대로 조회되고 그 다음 숫자 순서대로 조회된다.
-- order by :정렬하기
select*
from titanic_raw
where survived = 1
order by fare asc; #기본은 오름차순(asc생략가능)
select*
from titanic_raw
where survived = 1
order by fare desc; #내림차순
where에 조건을 걸고 그 다음으로 order by를 쓰고 정렬할 컬럼명을 쓴다 .
내림차순일땐 컬럼명 뒤에 desc를 쓴다
--산술연산자
select sibsp % parch as add_sibsp_parch
from titanic_raw;
# 함수 사용하기
-- distinct :중복 제거하기
select distinct(cabin) from titanic_raw;
-- count 함수: 총개수 확인하기
count 함수는 null 값 무시
select count(passengerid) as cnt
from titanic_raw;
select count(passengerid) from titanic_raw
where cabin is null;
-- 운임료 총합계 확인해보기
-- sum 함수는 null 값 무시
select sum(fare) as sum_fare
from titanic_raw;
-- 평균 운임료 확인해보기
-- avg 함수는 null 값 무시
select avg(fare) as avg_fare
from titanic_raw;
-- 운임료에대한 표준편차 확인해보기
-- std 함수는 null 값 무시
select std(fare) as std_fare
from titanic_raw;