코딩테스트

[프로그래머스 고득점 sql kit] 입양 시각 구하기(2) mysql

코앤미 2023. 9. 15. 14:36

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/59413

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 풀이

중요한 부분은 '존재 하지 않는 시간의 경우, 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 로 구하는 방식을 선택했다.