데이터 분석가
article thumbnail
Published 2023. 10. 5. 13:53
SQL-데이터 조작어 SQL
  • 이번 글에서는 SQL 기초문법 중의 하나인 데이터 조작어에 대해 설명하고자 한다.

교재 구매

  • 아래 교재내용을 토대로 진행해보겠습니다.
  • 기본 DB설정은 교재의 내용을 참고하시기 바랍니다.

https://www.yes24.com/Product/Goods/86544423

 

SQL로 맛보는 데이터 전처리 분석 - 예스24

SQL을 이용하여 현업에서 자주 사용되는 KPI 지표를 직접 추출해본다데이터 분석을 하기 위해서는 데이터베이스에 존재하는 데이터를 직접 추출할 수 있어야 한다. SQL은 우리가 데이터베이스에

www.yes24.com

데이터 조작

1) SELECT

  • 테이블에서 원하는 검색을 하기 위한 명령어
  • SQL 쿼리에서 핵심이 되는 명령어로 여러 조건을 달아 원하는 정보를 조회할 수 있다.
-- 기본 DB설정
USE classicmodels;

-- 기초 검색
select customernumber, phone
from customers;

select sum(amount)
from payments;

-- 컬럼명 변경
select count(productcode) as n_products
from products;

-- 교재 31p
-- distinct 중복 제외하고 데이터 조회!
select count(ordernumber) as 중복포함, count(distinct ordernumber) as 중복제거
from orderdetails;

-- where, between
select *
from orderdetails
where priceeach between 30 and 50;

-- where, 대소관계 연산자
select *
from orderdetails
where priceeach < 30;

-- where, in
select customernumber, country
from customers
where country in ('USA');

-- where, is null
select employeenumber
from employees
where reportsto is null;

-- where, like
-- %는 문자를 의미
select addressline1
from customers
where addressline1 like '%st%';

-- group by
SELECT country, city, count(customernumber) AS n_customers
FROM customers
GROUP BY country, city;

-- case when : if 조건문
-- p.46, USA 거주자의 수 계산, 그 비중을 구하자

select sum(case when country = 'USA' then 1 else 0 end) N_USA
from customers;

-- join
select *
from orders A left join customers B on A.customernumber = B.customernumber
where B.country = 'USA';

-- 58p
-- 윈도우 함수 : Rank, Dense_Rank, Row_Number
select
    buyprice,
    row_number() over(order by buyprice) rownumber,
    rank() over(order by buyprice) rnk,
    dense_rank() over(order by buyprice) denserank
from products;

2) INSERT

  • 테이블에 투플을 삽입하는 명령어
-- 교재 p.72 insert
INSERT INTO payments(customerNumber, checkNumber, paymentDate, amount)
VALUES (9999, 'ABC123', '2005-05-25', 30000.75);

-- select로 삽입됐는지 확인
SELECT *
from payments
where customerNumber = 9999;

3) UPDATE

  • 저장된 데이터를 수정하는 명령어
update payments
set paymenDate = Date('2005-05-30')
where customerNumber = 9999;    -- where가 주어지지 않으면 해당 테이블의 모든 투플에 대해 속성 값을 수정한다.

-- select로 수정됐는지 확인
SELECT *
from payments
where customerNumber = 9999;

4) DELETE

  • 저장된 데이터를 삭제하는 명령어
delete
from payments
where customerNumber = 9999;    -- where가 주어지지 않으면 해당 테이블의 모든 투플을 삭제하여 빈 테이블로 남긴다.
-- select로 삭제됐는지 확인
SELECT *
from payments
where customerNumber = 9999;

5) 정리

  • 과거 공부했던 요약 정리입니다.

'SQL' 카테고리의 다른 글

SQL - 코호트 분석, RFM  (0) 2023.10.12
SQL - 쿼리의 문법 순서  (0) 2023.10.12
SQL - Retention Rate, Churn Rate  (0) 2023.10.06
SQL-데이터 정의어  (0) 2023.10.05
profile

데이터 분석가

@이꾹꾹

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!