- 날짜 포맷
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)
'SQL 공부' 카테고리의 다른 글
| Ifnull / Coalesce 함수, 윈도우 함수 (0) | 2026.01.10 |
|---|---|
| 서브쿼리(상관/FROM), IN, EXISTS 함수, CTE(WITH) (0) | 2026.01.10 |
| UNION, JOIN (0) | 2026.01.10 |
| SQL 기초, case when (집계함수 포함), DELETE vs TRUNCATE vs DROP (0) | 2026.01.10 |
| DBeaver 설치하기 (MySQL 연결) (0) | 2026.01.10 |