문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/59413
문제 풀이
중요한 부분은 '존재 하지 않는 시간의 경우, count 값을 0으로 해서 통계 값에 내보내야 한다는 점이다.
따라서 hour 값을 0~ 23까지 증가시키며 각각의 시간마다 animal_outs 테이블에서 몇명의 입양이 존재했는지 count로 찾아서 추가해주면된다.
정답 코드
set @hour := -1;
select ( @hour := @hour + 1 ) as hour, (
select count(DATE_FORMAT(datetime, "%H"))
from animal_outs
where @hour = DATE_FORMAT(datetime, "%H")
) as count
from animal_outs
where @hour < 23;
정답 코드 2
with recursive time as(
select 0 as h
union
select h+1
from time
where h<23
)
select h as HOUR ,(select count(*)from animal_outs where date_format(datetime,'%H')=h) as count
from time
주의
date_format 에서 %h 사용시 문제가 생긴다!
오답 코드
select date_format(datetime,'%h') as HOUR,count(*) as COUNT
from animal_outs
group by date_format(datetime,'%h')
order by date_format(datetime,'%h')
위의 경우, 존재하지 않는 시간에 대한 통계치가 나오지 않는다.
ex) 3시에 입양건이 0건이면, 아예 row가 생기지 않는다.
따라서, 각 시간마다 count 로 구하는 방식을 선택했다.
'코딩테스트' 카테고리의 다른 글
요격시스템 c++ (그리디, 중복 구간 문제) (0) | 2023.10.04 |
---|---|
[백준 11967] 불켜기 c++ (완전 탐색) (1) | 2023.08.30 |
[백쥰 2638] 치즈 c++ (완전 탐색) (0) | 2023.08.30 |
[백준 18428] 감시 피하기 c++ (완전 탐색) (0) | 2023.08.29 |
[백준 17182] 우주 탐사선 c++ (플로이드 + 완전탐색 ) (0) | 2023.08.29 |