몬그로이

SQL 01 본문

Organizing Docs/SQL Docs

SQL 01

Mon Groy 2024. 6. 27. 20:00

colum 선택

select *

 

table 선택

FROM payments

 

Column명 이름 바꿔 조회하기

select order_id ord_no, price "가격",

 

대소문자 구별

WHERE cuisine_type='korean'

WHERE cuisine_type='Korean'

 

영문은 작은 따옴표(') 붙여주고

한글은 큰 따옴표 (") 붙여주기 - 문자 취급 

select name "이름", email "e-mail"

* e-mail 에는 dash 가 들어가 있으므로 문자로 취급해야 함


value 값 지정하여 row 선택

WHERE pay_type='card'

 

value 범위 지정하여 row 선택

WHERE gender <> 'male'

WHERE age between 21 and 23

WHERE age 21, 23

 

'해당 값을 포함하는' value 가 들어있는 row 선택

WHERE name in ("21, 25, 27")

WHERE name in ('윤주아', '정현준')

 

특정 문자를 일부분으로 갖는 value가 들어있는 row 선택

- 시작문자%

where name like '김%'

- %중간문자%

WHERE '%Next%'

- %끝문자

WHERE name like '%후'


 

조건 이어주기

 

- 조건 여러 개 넣기(교집합, '그리고') **21살 이상이고 성별이 male 인

WHERE age>=21

and gender='male'

 

- 조건 여러 개 넣기(교집합, '또는')**21살 이상 또는 성별이 male 인

WHERE age>=21

or gender='male'

 

- 조건 여러 개 넣기(교집합, '아닌') **21살 이상이지만 성별이 male 이 아닌(female인)

WHERE age>=21

not gender='male' 


데이터 조회와 연산

select food_preparation_time,

delivery_time,

food_preparation_time * delivery_time as total_time

from food_orders

 

합계와 평균 구하기

select sum(food_preparation_time) total_food_preparation_time,

           avg(delivery_time) avg_delivery_time

* Column 이름이 avg(delivery_time) 이라고 나오는데, 이를 지정해줄 수 있음

select avg(age) as average_of_age

** Column 이름이 avg(age) 로 나올 것을 average_of_age 로 나오게 함

 

테이블에 있는 모든 데이터의 개수 세기

select count(1) count_of_orders

from food_orders

*count 뒤의 괄호 안에 오는 1의 의미는 * 과 같아서 "모든것" 을 의미함 (* 또는 1 사용하면 됨)

 

테이블에 있는 데이터 중 특정 column 을 기준으로 중복 제거하여 개수 세기

select count(distinct customer_id) count_of_customers

from food_orders

*customer_id 의 합집합 수

**주문 건수가 10건인데 주문한 사람은 5사람일 때 5로 count 됨

 

최솟값, 최댓값 구하기

select min(price) min_price,

           max(price) max_price

FROM food_orders


@Query 어노테이션을 Repository에 적용한 예시

@Query("SELECT TOTAL(oi.quantity * oi.priceAtTime) FROM OrderItem oi")


예시 문제

주문 금액이 30,000원 이상인 주문건 갯수 구하기

select count(1) cnt_orders

FROM food_orders

where price >= 30000

 

주문 table 에서 한국음식의 평균 가격 구하기

select avg(price) as average_price

FROM food_orders

where cuisine_type='Korean'

 


음식 타입에 따라 합계 금액 구하기

select cuisine_type,

           sum(price) sum_of_price

from food_orders

group by cuisine_type

*두 column 을 골랐고, cuisine_type 끼리 묶는다 -> cuisine_type 에 따른 price의 합계를 보여주라는 

 

음식점별 주문 금액 최댓값 구하기

select restaurant_name,

          max(price) max_price_of_restaurant

from food_orders

group by restaurant_name

 

결제타입별 가장 최근 결제일 구하기

select pay_type,

           max(date) recent_date

FROM payments

group by pay_type

 


order by 는 기본적으로 오름차순 이므로 내림차순을 원하면 desc 를 붙여준다

order by sum(price) DESC

 

음식점별 주문 금액 최댓값 조회하기 - 최댓값 기준 내림차순 정렬

select restaurant_name,

           max(price) max_price

from food_orders

group by restaurant_name

order by max_price DESC

 

고객 이름 기준 오름차순 정렬하기

select *

from customers

order by name

* 어떤 column 을 조회할지 명시하지 않았기 때문에 전체 column 조회

**오름차순은 기본값이기 때문에 적지 않음

 

두 column 기준으로 정렬하는 것도 가능

select *

from customers

order by gender, name

 

 

특정 column 내 데이터 값 중 일부만 선택하여 바꾸기

select restaurant_name "원래 상점명",

           replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명" //(column, 원래값, 바꿀값)

from food_orders

where restaurant_name like '%Blue Ribbon%'

*ex) Blue Ribbon -> Pink Ribbon

 

특정 문자만 뽑아내기

select addr "원래 주소",

           substr(addr, 1, 2) "시도" //(column, 시작위치, 총 글자수)

from food_orders

where addr like '%서울특별시%'

*ex) 서울특별시 -> 서울

**substr 는 substring 의 줄임

 

concat 기능 사용해보기

select restaurant_name "원래 이름",

           addr "원래 주소",

           concat(restaurant_name, '-', cuisine_type) "음식타입별 음식점",

           concat('[', substring(addr, 1, 2), '] ', restaurant_name) "바뀐 이름"

from food_orders

where addr like '%서울%'

 

 

서울 지역의 음식 타입별 평균 음식 주문 금액 구하기

select substr(addr,1,2) "지역",

          cuisine_type,

          avg(price) "평균 음식 주문금액"

from food_orders

where addr like '서울%'

group by 1, 2 //substr(addr, 1, 2), cuisine_type 과 같은 의미

 

 

도메인별 평균연령과 고객 수

select count(1) "고객 수",

          avg(age) "평균 연령",

          substr(email, 10) "도메인"  //10번째 자리부터 끝까지 조회하겠

from customers

group by 3

 

 

[지역(시도)] 음식점 이름 (음식종류)' 컬럼 만들고, 총 주문 건수 구하기

SELECT concat('[', substr(addr,1,2),']', restaurant_name, '(', cuisine_type , ')') "음식점",

               count(1) "주문 건수"

from food_orders

group by 1

 

 

 

 

 

 

 

 

'Organizing Docs > SQL Docs' 카테고리의 다른 글

SQL 05  (0) 2024.06.29
SQL 03  (0) 2024.06.29
SQL04  (0) 2024.06.29
SQL 02  (0) 2024.06.27
SQL(Structured Query Language)  (0) 2024.05.25