SQL 공부

날짜 포맷, 날짜 함수

myun0506 2026. 1. 10. 22:34

 

- 날짜 포맷

select date(date) date_type,
	   date_format(date(date), '%Y') 'Year',
       date_format(date(date), '%m') 'Month',
       date_format(date(date), '%d') 'Day',
       date_format(date(date), '%w') 'Day of the Week'
       # 일 0 월 1 화 2 수 3 목 4 금 5 토 6
from payments
select date_format(date(date), '%Y') Year,
       date_format(date(date), '%m') Month,
       date_format(date(date), '%Y%m') YM,
       count(*) cnt
from food_orders f inner join payments p on f.order_id = p.order_id
where date_format(date(date), '%m') = '03'
group by 1, 2, 3
order by 1
  • date_format: 지정한 형식의 문자열로 변환해 문자열로 출력하는 함수
  • date(): 날짜 부분을 DATE 타입으로 추출하는 함수
col = 2024-05-01 13:45:30
DATE(col) # 2024-05-01
DATE_FORMAT(col, '%Y년 %m월 %d일') # '2024년 05월 01일'

 

 

- date에서 필요한 부분만 추출: year(date 형식의 값)

select *
from team_projects
where year(start_date) = 2022;

 

- 현재 날짜 반환: current_date()

select *
from team_projects
where current_date() between start_date and end_date;

 

- 날짜 차이 함수: datediff(이후 날짜 값, 이전 날짜 값)

select name, 
	   datediff(end_date, start_date) as working_days, # 실제 사용 o
	   (end_date - start_date) as wrong_working_days # 실제 사용 x
from team_projects;

 

- 두 날짜의 햇수 차이

select count(*)
from doctors
where timestampdiff(year, hire_date, current_date()) >= 2

select count(*) 
from doctors 
where hire_date <= date_sub(current_date(), interval 2 year)

 

  • timestampdiff(unit, start_datetime, end_datetime)
  • date_sub(datetime, interval # unit)