문과생의 데이터 연습

ntile & rank_percent & cume_dist 함수 사용하기! [MySQL] 본문

SQL/MySQL

ntile & rank_percent & cume_dist 함수 사용하기! [MySQL]

의인은 믿음으로 2022. 4. 29. 15:36
728x90

MySQL에서 ntile & rank_percent & cume_dist 함수 쓰는법을 알아봅시다! GOGO! 

1.) ntile & rank_percent & cume_dist                                                           

SELECT Continent, LifeExpectancy,
       ntile(3) over (order by LifeExpectancy) as Life_class,
       concat(round(percent_rank() over(order by LifeExpectancy), 1) * 100, '%') as rank_percent_life,
       concat(round(cume_dist() over(order by LifeExpectancy), 1) * 100, '%') as cume_dist_life 
       FROM country 
WHERE LifeExpectancy is not null 
GROUP BY Continent ;

오늘도 귀찮은 저는 코드 한번에 적었습니다 ㅋㅋ 

 

Ntile 함수는 등급을 정해줍니다. 가로안에 3이라고 적어면 3등급으로 나눠줍니다. 2면 2개의 등급으로, 

Percent_rank 함수는 상위 %를 구하는 함수입니다. (0부터 시작) 

cume_dist  누적분포도 입니다. (0부터 시작 X)

 

대륙 별 기대수명에 대한 등급 상위 %, 누적을 확인할 수 있어요!  

 

 

이번에는 partition 별로 나눠볼까요? 

SELECT * 
FROM(SELECT Continent, LifeExpectancy,
       ntile(3) over (partition by Continent order by LifeExpectancy) as Life_class,
       concat(round(percent_rank() over(partition by Continent order by LifeExpectancy), 1) * 100, '%') as rank_percent_life,
       concat(round(cume_dist() over(partition by Continent order by LifeExpectancy), 1) * 100, '%') as cume_dist_life 
       FROM country 
WHERE LifeExpectancy is not null) as Life  
ORDER BY rank_percent_life < 0.2 ;

파티션 별로 나눠진것을 확인할 수 있습니다. 

 

 

 

 

이렇게 해서 ntile & rank_percent & cume_dist 함수 사용법을 알아봤습니다. 

틀린부분이나 피드백부분이 있으면 댓글 부탁드립니다. 감사합니다!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
Comments