SQL

[SQL] 4주차 With / 문자열 / Case

난 훈이 2022. 3. 10. 22:04

With → 깔끔한 쿼리문 정리하기 위해 사용

 

select c.title,
       a.cnt_checkins,
       b.cnt_total,
       (a.cnt_checkins/b.cnt_total) as ratio
from
(
	select course_id, count(distinct(user_id)) as cnt_checkins from checkins
	group by course_id
) a
inner join
(
	select course_id, count(*) as cnt_total from orders
	group by course_id 
) b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id

위의 코드를 with절을 사용해서 정리해보기 ↓

with table1 as (
	select course_id, count(distinct(user_id)) as cnt_checkins from checkins
	group by course_id
), table2 as (
	select course_id, count(*) as cnt_total from orders
	group by course_id
)
select c.title,
       a.cnt_checkins,
       b.cnt_total,
       (a.cnt_checkins/b.cnt_total) as ratio
from table1 a inner join table2 b on a.course_id = b.course_id
inner join courses c on a.course_id = c.course_id

// 7~8번째 'Enter'를 사용하면 Error 발생함 (테이블 없음)

 

문자열 쪼개보기

ex) 이메일 주소에서 @앞의 아이디만 가져오거나, @뒤의 이메일 도메인을 가져오고 싶을 때

  • substring_index
select user_id, email, SUBSTRING_INDEX(email, '@', 1) from users
// @를 기준으로 텍스트를 쪼개고, 그 중 첫 번째 조각을 가져오기

select user_id, email, SUBSTRING_INDEX(email, '@', -1) from users
// @를 기준으로 텍스트를 쪼개고, 그 중 마지막 조각을 가져오기

 

문자열 일부만 출력하기

ex) orders 테이블에서 created_at을 날짜까지만 출력하게 해봅시다

  • substring
select order_no, created_at, substring(created_at,1,10) as date from orders
// SUBSTRING(문자열, 출력을 하고싶은 첫 글자의 위치, 몇개의 글자를 출력하고 싶은지)

 

Case → 특정 조건에 따라, 데이터를 구분해서 정리해주고 싶을 때

 

/*10000점보다 높은 포인트를 가지고 있으면 '잘 하고 있어요!', 
평균보다 낮으면 '조금 더 달려주세요!' 라고 표시해 주기 */
select pu.point_user_id, pu.point,
case 
when pu.point > 10000 then '잘 하고 있어요!'
else '조금 더 달려주세요!'
END as '구분'
from point_users pu