[SQL] date_format 출력타입 정렬하기

도리·2025년 2월 13일

programmers lv2.월별 잡은 물고기 수

문제)

월별 잡은 물고기의 수와 월을 출력하기.
잡은 물고기 수 컬럼명은 FISH_COUNT, 월 컬럼명은 MONTH로 해주세요.
결과는 월을 기준으로 오름차순 정렬해주세요.
단, 월은 숫자형태 (1~12) 로 출력하며 9 이하의 숫자는 두 자리로 출력하지 않습니다. 잡은 물고기가 없는 월은 출력하지 않습니다.

내 코드)

select count(*) as fish_count, date_format(time,"%c") as month
from  fish_info
group by date_format(time,"%c")
order by month asc;

결과)

1,2,3,.. 순이 아닌 1,12,3,4,6,7,... 순으로 12가 1 다음이라고 인식되었구나.
-> date_format은 str 으로 반환되는구나....

해결)

date_format(time,"%c") 대신

  1. month(date) 사용
  2. cast(date_format(time, "%c") as unsigned) 사용

이때 unsigned는 음수없는 정수형이다. (음수 0 처리)

profile
인공지능응용학과 졸업예정..

0개의 댓글