MySQL

MySQL) LIKE, CASE, IF, GROUP BY 구문 사용하기

567Rabbit 2024. 5. 14. 13:31

Like

: 문자열 안에 원하는 문자가 들어있는지 검색하는 키워드

 

-- 책 제목에 the가 들어있는 데이터를 가져오시오
select *
from books
where title like '%the%';


-- the로 시작하는
select *
from books
where title like 'the%';


-- the로 끝나는
select *
from books
where title like '%the';


-- pages 수는 100보다 크고, 책 제목에 the가 들어간 책을 가져오되 재고수량 내림차순으로 데이터를 3개만 가져오시오
select *
from books
where pages > 100 and title like '%the%'
order by stock_quantity desc 
limit 0,3;


-- 책 제목에, talk가 없는 데이터만 가져오시오
select *
from books
where title not like '%talk%';


-- 제목에 stories가 포함된 데이터를 제목만 조회하시오
select title
from books
where title like '%stories%';


-- author_lname에 공백이 들어있는 사람의 책 제목과 author_lname을 조회
select title, author_lname
from books
where author_lname like '% %';


-- stock_qauntity의 숫자가 두자리인 데이터만 가져오시오
-- 언더스코어 사용! _ ***
select *
from books
where stock_quantity like '__';   #( _ _ 두자리를 나타낸다.)

 

 

 

Case

 

-- 제목에 stories를 포함하고 있으면 Short Stories로 제목이 Just Kids와 일치하거나 제목에 Heartbreaking이 포함되어있으면 Memoir로, 그렇지 않으면 Novel이라고 표현하자.
select title, author_lname,
case
when title like '%stories%' then 'Shoort Stories'
when title = 'Just Kids' or title like '%Heartbreaking%' then 'Memoir'
else 'Novel'
end as 'TYPE'
from books;


-- 출판년도가 2000년 이상인 책들은 '최신책'이라고 하고, 그렇지 않은 책들은 '예전책'이라고 하여, type 컬럼을 만들자
select * , 
Case when released_year >= 2000 then '최신책'
else '예전책'
end as 'type'
from books
order by released_year;


-- 재고가 0 이상이고 50 이하이면 *, 51 이상이고 100 이하이면 **, 이도저도 아니면, ***로 하여 stock이라는 컬럼을 만들자
select * , 
Case 
when stock_quantity between 0 and 50 then '*'
when stock_quantity between 51 and 100 then '**'
else '***'
end as stock
from books;

 

 

 

If

 

-- 출판년도가 2000년 이상인 책들은 '최신책'이라고 하고, 그렇지 않은 책들은 '예전책'이라고 하여, type 컬럼을 만들자
select *,
if(released_year >= 2000, '최신책', '예전책') as type
from books;



-- pages 컬럼의 값이 300보다 크면 '긴 책'이라고 하고, 그렇지 않으면 '짧은책'이라고 하여 새로운 컬럼 book_type을 만들자
select * ,
if(pages > 300, '긴책', '짧은책' )
from books;

 

 


Group By

: ~별로 묶어서 처리하자

 

# having은 group by의 조건절로, group by 뒤에는 where이 올 수 없고 having으로 조건절을 써야 한다

-- author_lname별로 몇권의 책을 썼는지 갯수를 나타내세요
select title, author_lname, count(author_lname) as count
from books
group by author_lname;


-- 년도별 stock_quantity의 평균값이 70보다 큰 책들의 년도와 평균값?
select released_year, avg( stock_quantity ) as avg_stock
from books 
group by released_year having avg_stock >= 70 ;