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.
Input Format
The EMPLOYEES table is described as follows:

Note: Salary is per month.
Constraints
1,000 < Salary < 10^5
Sample Input

Sample Output
2061
Explanation
The table below shows the salaries without zeros as they were entered by Samantha:

Samantha computes an average salary of 98.00 . The actual average salary is 2159.00.
The resulting error between the two calculations is 2159.00-98.00. Since it is equal to the integer 2061, it does not get rounded up.
해설
Samantha는 EMPLOYEES 테이블에 있는 모든 직원의 평균 월급을 계산하는 작업을 맡았으나, 그녀는 키보드의
0키가 고장난 상태에서 작업을 완료했고, 0이 제거된 상태로 월급을 계산하게 되었다. 이제 그녀는 실제 평균 월급과 잘못된 계산으로 도출된 평균 월급 간의 차이를 구하고, 그 차이를 다음 정수로 올림한 결과를 알고 싶어 한다.
SELECT
CEIL(
(SELECT
AVG(Salary)
FROM
EMPLOYEES)
-
(SELECT
AVG(REPLACE(Salary, '0', ''))
FROM
EMPLOYEES)
)
-- CEIL 함수는 소수점 이하를 제거하면서 무조건 값을 올림 처리, 특정 자리 올림 옵션은 제공 X
SELECT CEIL(4.3) AS RoundedNumber;
-- 5
SELECT CEIL(-2.9) AS RoundedNumber;
-- -2
챗지피티한테 물어보니까 아래와 같은 함수를 짜줬는데, 생소한 함수가 있어 추가로 정리했다.
SELECT
CEIL(
(SELECT AVG(Salary) FROM EMPLOYEES) -
(SELECT AVG(CONVERT(REPLACE(Salary, '0', ''), UNSIGNED)) FROM EMPLOYEES)
) AS ErrorDifference;
- CONVERT 함수: MySQL에서 데이터 타입을 변환할 때 사용하는 함수입니다. CONVERT(expression, type) 형식을 사용하며, expression을 지정한 type으로 변환합니다.
- UNSIGNED: MySQL의 데이터 타입에서 부호 없는 정수를 의미합니다. 정수 값에서 음수를 제외하고 0 이상의 값만 가지는 타입으로 변환합니다. 예를 들어, UNSIGNED INT는 음수를 허용하지 않고 0에서 4,294,967,295 사이의 값만 허용합니다.
SELECT CONVERT(INT, '123');
-- 문자열 '123'을 정수형 INT로 변환
SELECT CONVERT('123', UNSIGNED);
-- 문자열 '123'을 부호 없는 정수형 UNSIGNED로 변환
- CAST 함수 : CAST(expression AS data_type) 형식을 사용하여, 데이터 타입을 변환할 때 사용하는 함수.
SELECT CAST('123' AS INT);
-- 문자열 '123'을 정수형 INT로 변환
묵시적 타입 변환
SELECT
CEIL(
(SELECT AVG(Salary) FROM EMPLOYEES) -
(SELECT AVG(REPLACE(Salary, '0', '') + 0) FROM EMPLOYEES)
) AS ErrorDifference;
- 변환된 값은 문자열이지만, + 0을 더해주면 MySQL이 이를 숫자로 자동 변환합니다. 이는 묵시적 타입 변환이라고 불립니다.
- 하지만, MySQL에서는 REPLACE 함수로 0을 제거한 결과를 사용할 때, MySQL이 자동으로 적절하게 문자열을 숫자로 변환해서 처리해기 때문에 그래서 굳이 + 0을 하지 않아도 쿼리가 정상적으로 작동함.
- 다만, 추가로 찾아보니 묵시적 타입 변환보다는 CAST, CONVERT와 같은 명시적 타입 변환을 해주는 것이 좋다고 해서 앞으로는 그렇게 하려고 함.
'SQL > HackerRank' 카테고리의 다른 글
[MySQL/HackerRank] Population Density Difference (0) | 2024.08.13 |
---|---|
[MySQL/HackerRank] Japan Population (0) | 2024.08.13 |
[MySQL/HackerRank] Average Population (0) | 2024.08.13 |
[MySQL/HackerRank] Revising Aggregations - Averages (0) | 2024.08.13 |
[MySQL/HackerRank] Revising Aggregations - The Sum Function (0) | 2024.08.13 |