1. The Blunder
https://www.hackerrank.com/challenges/the-blunder/problem?isFullScreen=true
The Blunder | HackerRank
Query the amount of error in Sam's result, rounded up to the next integer.
www.hackerrank.com
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.: actual-miscalculated average monthly salaries), and round it up to the next integer.
EMPLOYEES 테이블에는 월급(salary)값만 들어있으니까
- 그 월급에서 0을 전부 제거한 값을 쿼리 안에서 만들어서
- 그걸 이용해 잘못된 평균을 계산한 다음
- 실제 평균과 비교해서 차이를 구해야 합니다.
SELECT CEIL(
AVG(salary) - AVG(
CAST(
COALESCE(NULLIF(REPLACE(salary, '0', ''), ''), '0') AS DECIMAL(20,4)
)
)
) AS error_amount
FROM EMPLOYEES;
COALESCE(NULLIF(REPLACE(salary, '0',''), ''), '0') 해석
- REPLACE(salary, '0', '')
- 급여 숫자에서 모든 0을 제거합니다.
- 예)
- 10500 → '15'
- 900 → '9'
- 0 → '' (모두 0이면 빈 문자열이 됨)
- NULLIF(<결과>, '')
- 결과가 빈 문자열이면 NULL로 바꿔줍니다.
- 즉, “공백을 NULL로 바꾼다”가 맞는 해석입니다. (반대 아님!)
- 예)
- '15' → 그대로 '15' (공백이 아니니까)
- '' → NULL
- COALESCE(<결과>, '0')
- NULL이면 '0'으로 채운다는 뜻입니다.
- 왜 0으로 채우냐?
- Samantha는 0 키가 안 눌려서 숫자 안의 0들을 모두 빼고 쳤어요.
- 그런데 원래 급여가 0(혹은 00)처럼 모두 0으로만 이루어진 값이라면, 0을 다 빼고 나면 아무 숫자도 남지 않음(=빈 문자열) → 이건 “잘못 입력한 값”을 0으로 보는 게 자연스럽습니다.
- 즉, “모두 0이던 급여”의 오계산 결과는 0이어야 해요. 그래서 COALESCE(..., '0')로 0을 넣어줍니다.
CAST(..AS DECIMAL(20,4)) 구조
1. CAST(..AS DECIMAL(20,4)) 구조
- CAST → SQL 표준 함수, 데이터 타입을 변환할 때 사용
- AS DECIMAL(20,4) → 바꿀 타입을 지정
- DECIMAL = 고정 소수점 타입
- (20,4) = 전체 20자리, 그중 소수점 4자리
2. 왜 DECIMAL을 쓰나?
- FLOAT나 DOUBLE은 부동소수점 오차가 발생할 수 있음 (예: 0.1 + 0.2 ≠ 0.3 정확히 안 나옴)
- DECIMAL은 정확한 계산이 가능 → 급여, 금액, 회계 데이터에서 필수
- (20,4)를 주면 정수부 최대 16자리 + 소수부 4자리까지 안전하게 저장
3. 작성 쿼리에서의 의미
CAST(COALESCE(NULLIF(REPLACE(salary, '0', ''), ''), '0') AS DECIMAL(20,4))
- REPLACE 결과(문자열)를
- 소수점 4자리까지 계산 가능한 정밀 숫자로 변환
- 이렇게 해야 AVG()가 정확하게 동작하고, 오차 없이 CEIL() 적용 가능
만약 급여가 억단위 이상이고, 평균도 소수점까지 정확하게 보고싶다면 DECIMAL(20,4)정도면 충분합니다.
(급여 데이터가 작으면 DECIMAL(10,2) 정도로 줄여도 됨
2. Top Earners
https://www.hackerrank.com/challenges/earnings-of-employees/problem?isFullScreen=true
Top Earners | HackerRank
Find the maximum amount of money earned by any employee, as well as the number of top earners (people who have earned this amount).
www.hackerrank.com
We define an employee's total earnings to be their monthly salary x months worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as 2 space-separated integers.
SELECT
MAX(salary * months) as max_salary,
COUNT(*) AS cnt
FROM Employee
WHERE salary * months =(SELECT
max(salary * months) AS MAX_SALARY
FROM Employee)
point!
Then print these values as 2 space-separated integers.
= 두개의 값을 출력하는데, 그 값들 아이에 공백을 하나 넣어서 구분하라
대부분의 sql환경에서는 SELECT문을 사용하면 여러 개의 컬럼을 공백으로 구분하여 출력하기 때문에 별도의 추가적인 작업 없이 쿼리 결과가 자동으로 이 형식으로 나옵니다.
'코딩 테스트 > 02. SQL' 카테고리의 다른 글
| [Hacker Rank] SQL Basic 'Weather Obvervation Station 18' (Medium) (0) | 2025.08.17 |
|---|---|
| [Hacker Rank] SQL Basic 'The PADS' (medium) (3) | 2025.08.17 |
| [HackerRank] SQL Basic (easy)(5) (1) | 2025.08.15 |
| [HackerRank] SQL Basic (easy)(4) (2) | 2025.08.14 |
| [HackerRank] SQL Basic (easy)(3) (1) | 2025.08.13 |
