https://school.programmers.co.kr/learn/courses/30/lessons/131530#qna
round
ceil
floor
truncate
case when 까지 별여별 함수를 다 써서 테스트 해보다가
결국 floor, truncate 함수로 귀결!!!!
** 연습해본 쿼리
-- PRODUCT 테이블
1. 데이터 확인해보기
SELECT round(PRICE/10000,0)*10000 as price_group ,count(*) as cnt
from PRODUCT
group by price_group
order by price_group desc
SELECT price,round(PRICE/10000,0)*10000 as price_group ,ceil(PRICE/10000) as price_group2,
PRICE/10000 as price_group3
from PRODUCT
group by price_group
order by price_group desc
SELECT price, round(PRICE/10000,0) , round(PRICE/10000,0)*10000 as price_group
from PRODUCT
SELECT
case when round(PRICE/10000,0)*10000<10000 then '1만원미만'
when round(PRICE/10000,0)*10000<20000 then '1만원미만'
when round(PRICE/10000,0)*10000<30000 then '1만원미만'
when round(PRICE/10000,0)*10000<40000 then '1만원미만'
when round(PRICE/10000,0)*10000<50000 then '1만원미만'
-- 코드를 입력하세요
SELECT TRUNCATE((price / 10000),0) * 10000 AS PRICE_GROUP , COUNT(PRODUCT_ID) AS PRODUCTS
FROM PRODUCT
GROUP BY PRICE_GROUP
ORDER BY PRICE_GROUP ASC
SELECT floor(price / 10000) * 10000 as PRICE_GROUP, count(*) as PRODUCTS
from PRODUCT
group by floor(price / 10000) * 10000
order by 1;
-- PRODUCT 테이블
SELECT
case when 0<PRICE<10000 then '1만원미만'
when 10000<=PRICE<20000 then '2만원미만'
when 20000<=PRICE<30000 then '3만원미만'
when 30000<=PRICE<40000 then '4만원미만'
when 40000<=PRICE<50000 then '5만원미만'
when 50000<=PRICE<60000 then '6만원미만'
when 60000<=PRICE<70000 then '7만원미만'
when 70000<=PRICE<80000 then '8만원미만'
when 80000<=PRICE<90000 then '9만원미만'
else '9만원이상' end as price_group ,
count(product_id) as PRODUCTS
from PRODUCT
group by price_group
order by price_group
-- 코드를 입력하세요
-- PRODUCT 테이블
-- price 가 19000 의경우, round 는 20000, ceil 함수 20000, floor 는 10000, truncate 10000
-- 따라서 floor 함수 또는 truncate 함수만 써야함
SELECT price,
round(PRICE/10000)*10000 as price_group_r, -- 반올림
ceil(PRICE/10000)*10000 as price_group_c, -- 무조건 소수점 첫째에서 올림 - 이것은 절대 쓰면 안됨
floor(PRICE/10000)*10000 as price_group_f, -- 내림
TRUNCATE((price / 10000),0) * 10000 AS PRICE_GROUP_t,
count(product_id) as PRODUCTS
from PRODUCT
group by price_group_r
order by price_group_r
차이를 보면 알수 있다!!!! ceil은 절대 쓰면안됨!!! 무조건 올림
정답1
-- 코드를 입력하세요
-- PRODUCT 테이블
-- price 가 19000 의경우, round 는 20000, ceil 함수 20000, floor 는 10000, truncate 10000
-- 따라서 floor 함수 또는 truncate 함수만 써야함
SELECT
floor(PRICE/10000)*10000 as price_group_f, -- 내림
count(product_id) as PRODUCTS
from PRODUCT
group by price_group_f
order by price_group_f
정답2
SELECT TRUNCATE((price / 10000),0) * 10000 AS PRICE_GROUP , COUNT(PRODUCT_ID) AS PRODUCTS
FROM PRODUCT
GROUP BY PRICE_GROUP
ORDER BY PRICE_GROUP ASC
'「SQL초급떼기' 카테고리의 다른 글
코딩테스트 연습GROUP BY입양 시각 구하기(2) (0) | 2023.04.02 |
---|---|
코딩테스트 연습GROUP BY입양 시각 구하기(1) (0) | 2023.04.02 |
코딩테스트 연습GROUP BY년, 월, 성별 별 상품 구매 회원 수 구하기 (0) | 2023.04.02 |
코딩테스트 연습GROUP BY진료과별 총 예약 횟수 출력하기 (0) | 2023.04.02 |
코딩테스트 연습GROUP BY카테고리 별 도서 판매량 집계하기 (0) | 2023.04.02 |
댓글