Tools/- SQL

[SQL] solvesql | 유량(Flow)와 저량(Stock) | strftime로 날짜 추출하기 | SQLite

스위민 2025. 2. 9. 22:44

문제

https://solvesql.com/problems/flow-and-stock/

 

https://solvesql.com/problems/flow-and-stock/

 

solvesql.com

 

코드

select year as "Acquisition year", 
  acquisition as "New acquisitions this year (Flow)", 
  sum(acquisition) over (order by year) as "Total collection size (Stock)"
from
(select substring(acquisition_date, 1, 4) as year, count(distinct artwork_id) as acquisition
from artworks
group by 1
having substring(acquisition_date, 1, 4) is not null) as t

-- 7분 성공

 

문제 풀이

  • 날짜에서 연도 추출하기

1. substring (컬럼명, 시작위치, 길이)

2. strftime ('%단위', 컬럼명) : '%Y'로 연도 추출

 

SQLite는 시간 함수로 strftime을 지원한다.

MySQL에서는 date_format을 사용하면 되겠다.

 

date_format (컬럼명, %단위')

 

느낀 점

SQLite와 MySQL 문법을 구별해서 외워놔야겠다 ..!