SQL 스터디/HackerRank

[해커랭크] MySQL 숫자를 문자로 변환하기(CAST) - The Blunder

황금붕어빵 2023. 9. 11. 21:44

 


 

 

The Blunder | HackerRank

Query the amount of error in Sam's result, rounded up to the next integer.

www.hackerrank.com

점점 문제가 길어지고 영어 공부도 같이 하는 것 같습니다 :)

 

이번 문제는 Samatha라는 직원이 전 직원의 평균 급여를 계산하고 있는데 숫자 '0'키가 고장났다는 상황을 가정하여 실제 평균급여와 '0'을 누르지 못했을 때의 평균급여 금액의 차이를 구하는 문제입니다.

문제)
Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize her keyboard's 0 key was broken until after completing the calculation. She wants your help finding the difference between her miscalculation (using salaries with any zeros removed), and the actual average salary.

Write a query calculating the amount of error (i.e.:  average monthly salaries), and round it up to the next integer.

출처 : 해커랭크

REPLACE 함수를 활용해서 숫자 0을 제거를 해주어야 할 것 같은데요.

 

REPLACE 함수는 숫자 타입의 컬럼에서는 사용이 불가하고 문자열일때 사용이 가능합니다. 그래서 문자로 바꿀 수 있는 CAST 함수를 추가로 활용해야 합니다.

select avg(salary) - avg(replace(cast(salary as char), "0", ""))
from employees

숫자 '0' 키가 고장 난 경우의 평균급여를 구할 때는 먼저 CAST 함수를 통해 salary를 문자열로 바꿔준 후에 0을 제외를 해줍니다.

 

그리고 정수 부분까지 올림 처리를 해야하므로 CEIL 함수를 감싸주면서 쿼리를 작성하면 됩니다.

select ceil(avg(salary) - avg(replace(cast(salary as char), "0", "")))
from employees