본문 바로가기
DB/SQL 예제

함수 예제 1

by ssury94 2024. 11. 28.

세팅

 

데이터베이스 test6
테이블 books
컬럼 id - int, pri, not null, auto increment
title - varchar(100)
author_fname - varchar(100)
author_lname - varchar(100)

released_year - int
stock_quantity -int
pages - int
더보기
INSERT INTO books (title, author_fname, author_lname, released_year, stock_quantity, pages)
VALUES
('The Namesake', 'Jhumpa', 'Lahiri', 2003, 32, 291),
('Norse Mythology', 'Neil', 'Gaiman',2016, 43, 304),
('American Gods', 'Neil', 'Gaiman', 2001, 12, 465),
('Interpreter of Maladies', 'Jhumpa', 'Lahiri', 1996, 97, 198),
('A Hologram for the King: A Novel', 'Dave', 'Eggers', 2012, 154, 352),
('The Circle', 'Dave', 'Eggers', 2013, 26, 504),
('The Amazing Adventures of Kavalier & Clay', 'Michael', 'Chabon', 2000, 68, 634),
('Just Kids', 'Patti', 'Smith', 2010, 55, 304),
('A Heartbreaking Work of Staggering Genius', 'Dave', 'Eggers', 2001, 104, 437),
('Coraline', 'Neil', 'Gaiman', 2003, 100, 208),
('What We Talk About When We Talk About Love: Stories', 'Raymond', 'Carver', 1981, 23, 176),
("Where I'm Calling From: Selected Stories", 'Raymond', 'Carver', 1989, 12, 526),
('White Noise', 'Don', 'DeLillo', 1985, 49, 320),
('Cannery Row', 'John', 'Steinbeck', 1945, 95, 181),
('Oblivion: Stories', 'David', 'Foster Wallace', 2004, 172, 329),
('Consider the Lobster', 'David', 'Foster Wallace', 2005, 92, 343);

 

-- 타이틀의 공백을 ->으로 바꿔서 나오도록 조회

SELECT title, replace(title,' ','->')as title
from books b ;

 

 

-- 다음 컬럼처럼 나오게 조회하세요.

SELECT author_lname as forwards, reverse(author_lname) as backwards
from books b ;

 

 

 

★--  대문자 풀네임으로 조회하세요.

SELECT concat(upper(author_fname),' ',upper(author_lname)) as full_name_in_caps
FROM books b ;

내가 작성한 코드.. 원하는 결과는 나왔지만 어퍼를 몇번쓴거야 

SELECT upper(concat(author_fname,' ',author_lname))as full_name_in_caps
from books b ;

선생님께서 작성하신 코드 // 이쪽이 더 코드가 깔끔합니다.

 

-- 타이트컬럼과 년도컬럼을 합치되 was released in 이 들어가도록 합쳐서 조회하세요.

SELECT concat(title,' was released in ',released_year)as blurb
FROM books b ;

 

 

 

-- 타이틀과 타이틀에 적힌 글자 개수가 나오도록 조회하세요.

SELECT title, CHAR_LENGTH(title)as character_count
from books b ;

 

 

 

-- 숏타이틀은 앞에서 10글자까지만, 뒤에 ...이 나오도록 만들고

author는 이름 두개 컬럼을 합치고, quantitiy는 원래 숫자에 in stock이 붙도록 조회하세요.

SELECT concat(substr(title,1,10),'...')as short_title,
concat(author_lname,',',author_fname)as author,
concat(stock_quantity,' in stock')as quantity
FROM books b ;

 


* 함수 사용할땐 순서를 잘 생각하자.

10글자까지만 나타낸 다음에 > substr / 합칠것을 생각하기 >concat

* 하나 입력할때마다 실행해보며 오류가 나는지 돌다리두들기며 건너기