SQL

함수와 CASE/IF문

hyungminjeon 2024. 5. 30. 21:36

[실습쿼리]

-- 숫자 연산 예시
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
from food_orders

-- 갯수 구하기
select count(*) count_of_orders,
       count(distinct customer_id) count_of_customers
from food_orders

-- 최솟값, 최댓값 구하기
select min(price) min_price,
       max(price) max_price
from food_orders

-- Group by 예시
select cuisine_type,
       sum(price) sum_of_price
from food_orders
group by cuisine_type

-- Replace 예시
select restaurant_name "원래 상점명",
       replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명"
from food_orders
where restaurant_name like '%Blue Ribbon%'

-- Replace 예시2
select addr "원래주소",
       replace(addr, "문곡리", "문가리") "바뀐주소"
from food_orders
where addr like "%문곡리%";

-- Substring 예시
select addr "원래 주소",
       substr(addr, 1, 2) "시도"
from food_orders
where addr like '%서울특별시%'

-- Concat 예시
select restaurant_name "원래 이름",   
       addr "원래 주소",
       concat('[', substring(addr, 1, 2), '] ', restaurant_name) "바뀐 이름",
       concat(restaurant_name, '-', cuisine_type) '음식타입별 음식점'
from food_orders
where addr like '%서울%';

-- if문 예시
select restaurant_name,
       cuisine_type "원래 음식 타입",
       if(cuisine_type='Korean', '한식', '기타') "음식 타입"
from food_orders

-- if문 예시2
select addr "원래 주소",
       if(addr like '%평택군%', replace(addr, '문곡리', '문가리'), addr) "바뀐 주소"
from food_orders
where addr like '%문곡리%'

-- if문 예시3
select substring(if(email like '%gmail%', replace(email, 'gmail', '@gmail'), email), 10) "이메일 도메인",
       count(customer_id) "고객 수",
       avg(age) "평균 연령"
from customers
group by 1

select case when cuisine_type = "Korean" then '한식'
			when cuisine_type = "Chinese" then '중식'
			when cuisine_type = "Japanese" then '일식'
			when cuisine_type in ('American') then '아메리카'
			else '기타' end '음식타입',
			cuisine_type
from food_orders

-- case when 실습1
select order_id,
       price,
       quantity,
       case when quantity=1 then price
            when quantity>=2 then price/quantity end "음식 단가"
from food_orders

-- case 실습 
-- 10세 이상, 30세 미만의 고객의 나이와 성별로 그룹 나누기 (이름도 같이 출력)
select case when (age between 10 and 19) and gender = 'male' then '10대 남성'
		 	when (age between 10 and 19) and gender = 'female' then '10대 여성'
		 	when (age between 20 and 29) and gender = 'male' then '20대 남성'
		 	when (age between 20 and 29) and gender = 'female' then '20대 여성'
		 	end '고객분류',
		 	name,
		 	age,
		 	gender
from customers
where age between 10 and 29

-- case 실습2
select case when cuisine_type = 'Korean' then '한식'
			when cuisine_type in ('Japanese', 'Chinese','Thai','Vietnamese','Indian') then '아시아식'
			else '기타' end '음식 종류'
from food_orders

select restaurant_name,
       price/quantity "단가",
       cuisine_type,
       order_id,
       case when (price/quantity <5000) and cuisine_type='Korean' then '한식1'
            when (price/quantity between 5000 and 15000) and cuisine_type='Korean' then '한식2'
            when (price/quantity > 15000) and cuisine_type='Korean' then '한식3'
            when (price/quantity <5000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식1'
            when (price/quantity between 5000 and 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식2'
            when (price/quantity > 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식3'
            when (price/quantity <5000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타1'
            when (price/quantity between 5000 and 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타2'
            when (price/quantity > 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타3' end "식당 그룹"
from food_orders;

[정리 및 알게 된점]

Dbeaver를 통해 데이터베이스를 연결하는 것부터 시작하여 SELECT, FROM, WHERE, GROUP BY, ORDER BY 절들을 작성하고 비교연산, BETWEEN, IN, LIKE 등의 필터링을 학습하였다.

SUM, AVG, COUNT, MAX, MIN과 같은 함수들을 이용하여 계산식을 처리하는 방법을 배웠고, GROUP BY를 통해서 카테고리를 범주별로 묶는 연습을 하였다.

REPLACE, SUBSTRING, CONCAT과 같은 문자 포맷을 가공하기 위해 사용되는 함수들과,  IF, CASE문처럼 조건에 따라 포맷을 다르게 변경해야 할 때 사용되어지는 조건문에 대해서도 학습하였다.

문자 포맷 가공함수들은 SELECT문 안에서 서로 같이 사용될 수 있어, 여러 함수들을 동시에 사용하는 것에 익숙해지는데에 다소 연습이 필요하였다.  

'SQL' 카테고리의 다른 글

SQL Queries 실습  (0) 2025.03.28
SQL 연습 DDL, DML  (0) 2025.03.27
Pivot table  (0) 2024.06.04
Sub Query  (1) 2024.06.03
CASE/IF문 실습  (0) 2024.05.31