-
[프로그래머스 Level 4] 입양 시각 구하기 (2)SQL 문제 풀이 2024. 1. 4. 00:32
테이블 정보
문제
보호소에서는 몇 시에 입양이 가장 활발하게 일어나는지 알아보려 합니다.
0시부터 23시까지, 각 시간대별로 입양이 몇 건이나 발생했는지 조회하는 SQL문을 작성해주세요.
이때 결과는 시간대 순으로 정렬해야 합니다.
결과 예시
문제 풀이 (MySQL)
SET @HOUR = -1; SELECT (@HOUR := @HOUR + 1) AS HOUR, (SELECT COUNT(HOUR(B.DATETIME)) FROM ANIMAL_OUTS B WHERE @HOUR = HOUR(B.DATETIME) ) AS COUNT FROM ANIMAL_OUTS A LIMIT 24;
위에 예시를 보다시피 7시부터 데이터가 존재한다.
그러므로 단순히 HOUR(DATETIME)으로 GROUP BY를 통해 묶어준다면 0 ~ 6시까지의 데이터는 행으로 잡히지 않기 때문에 0 ~ 23시까지의 값을 인위적으로 만들어야 된다고 생각했다.
인위적으로 값을 만들기 위해, SET을 통해 변수를 직접 만들었다.
SET 이외의 명령문에서는 = 가 비교연산자로 취급되므로,
SELECT로 변수를 선언하고 대입할 때는 := 를 사용한다.
초기값을 -1로 설정하고 @HOUR := @HOUR + 1을 통해 값을 1씩 증가 시켜주는데,
마지막에 LIMIT 24로 제한해서 0 ~ 23시까지의 값만 나오도록 설정해준다.
또한 LIMIT 24가 아니라 WHERE절을 사용해도 될 것 같다.
Oracle에서는 MySQL의 @SET과 비슷한 방식으로 변수 선언하는 방식도(Oracle PL/SQL에) 존재하지만
규칙에 따라 순번을 생성하는 Sequence 객체가 존재한다.
CREATE SEQUENCE를 사용하면 편할 거 같긴 한데
프로그래머스에서 CREATE 문 사용 시 권한 오류가 뜨기 때문에 다른 방법을 고안해 봐야 할듯하다.https://hyeon-joo.tistory.com/3
'SQL 문제 풀이' 카테고리의 다른 글
[프로그래머스 Level 4] 우유와 요거트가 담긴 장바구니 (0) 2024.01.25 [LeetCode Hard] 601. Human Traffic of Stadium (0) 2024.01.16 [LeetCode Medium] 1341. Movie Rating (0) 2024.01.12 [LeetCode Hard] 185. Department Top Three Salaries (2) 2024.01.07 [LeetCode Medium] 550. Game Play Analysis IV (0) 2024.01.05