문제 보기

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

풀이 방법

서브 쿼리를 사용해 상품이 속한 가격대를 지정하고,
메인 쿼리에서 가격대 별로 GROUP BY 하기
FROM (
    SELECT TRUNCATE(PRICE, -4) AS PRICE_GROUP
    FROM PRODUCT
    ) AS PRODUCT2

 

숫자함수 FLOOR (+ ROUND, CEIL)

TRUNCATE는 몰라도 ROUND는 반올림, FLOOR는 내림, CEIL은 올림이라는 건 다들 알 것이다.

그런데 ROUND는 FLOOR, CEIL와 파라미터 형태가 좀 다르다.

 

ROUND

ROUND(123.45, 1) -- 123.4
ROUND(123.45, -1) -- 120

 

ROUND는 두 개의 파라미터를 받는다.
첫 파라미터는 반올림 할 숫자, 두 번째 파라미터는 반올림 할 소숫점 자릿수이다.
위와 같이 1일 경의 소숫점 첫째자리까지, -1일 경우 소숫점 -첫째자리(일의 자리)까지 반올림을 한다.

 

참고

 

MySQL ROUND() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

FLOOR, CEIL

FLOOR(123.45) -- 123
CEIL(123.45) -- 124

 

FLOOR, CEIL 함수는 파라미터를 한 개만 받으며 정수로 내림, 올림 한다.

 

참고

 

MySQL FLOOR() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

 

MySQL CEIL() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

TRUNCATE

우리는 정수가 아니라 1000의 자리 내림을 하고 싶다.
그러나 FLOOR 함수로는 자릿수를 지정해주지 못 한다.
FLOOR와 비슷하면서 파라미터를 2개 받는 함수는 없을까?

 

TRUNCATE(123.45, -1) -- 120

 

TRUNCATE 함수가 그 역할을 하고 있다.
정확히는 해당 소숫점 자릿수 아래를 잘라버리는 함수로 예시와 같을 경우 1의자리 에서 내림하는 꼴이 된다.

 

참고

 

MySQL TRUNCATE() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

TRUNCATE와 TRUNCATE()

TRUNCATE라는 테이블 초기화 명령어와 헷갈리는 사람도 있을 것이다.

숫자 함수인 TRUNCATE() 테이블 초기화 명령어 TRUNCATE를 잘 구분 하도록 하자.

 

참고

 

SQL DROP TABLE, TRUNCATE TABLE

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

 

전체 코드

SELECT PRICE_GROUP, COUNT(*) AS PRODUCTS
FROM (
    SELECT TRUNCATE(PRICE, -4) AS PRICE_GROUP
    FROM PRODUCT
    ) AS PRODUCT2
GROUP BY 1
ORDER BY 1

 

 

GitHub 링크

 

CodingTest_AutoSave/프로그래머스/2/131530. 가격대 별 상품 개수 구하기 at main · MetroDefro/CodingTes

모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.

github.com

+ Recent posts