coding/sql 코딩테스트
[solvesql] 유량(Flow)와 저량(Stock)
임이레
2025. 1. 31. 17:17
with calc_table as (
select YEAR(acquisition_date) as acq_year
,count(artwork_id) as cnt
from artworks
group by 1
)
, calc_table2 as (
select *
,lag(cnt, 1) over (order by acq_year asc) as prev_cnt
from calc_table
where acq_year is not null
)
select acq_year as 'Acquisition year'
, cnt as 'New acquisitions this year (Flow)'
, sum(cnt) over (order by acq_year) as 'Total collection size (Stock)'
from calc_table2
order by 1 asc ;
첫번째 시도의 코드 (정답으로 인정은 됨)
처음에는 문제를 이해하기 위해
artworks라는 테이블 내의 소장 년도에 따라 먼저 count 를 통해 새롭게 소장하게 된 작품의 수를 먼저 구한 후
prev_cnt 를 구해서 이전의 소장 년도와 비교하며 보았다.
결과적으로 prev_cnt 는 상관 없는 컬럼이지만 이해가 가지 않는 상태에서는 파생변수를 만들어가며 테이블을 구조 분석하는 것도 좋은 방법인 것 같다.
두번째 시도의 코드
with calc_table as (
select YEAR(acquisition_date) as acq_year
,count(artwork_id) as cnt
from artworks
where YEAR(acquisition_date) is not null
group by 1
)
select acq_year as 'Acquisition year'
, cnt as 'New acquisitions this year (Flow)'
, sum(cnt) over (order by acq_year) as 'Total collection size (Stock)'
from calc_table
order by 1 asc ;
window function 을 통해 누적합계를 구했다.
데이터분석가가 되는 과정은 길고도 험한 길이다. 컴퓨터 공학, 통계, 비즈니스 분석 방법 등 참 많은 공부가 필요한 영역이다.
그러나 신입 데이터 분석가를 준비하며 sql ,python 활용에 있어서는 지속적인 노력을 통해 유연하게 사용할 수 있는 능력을 탑재해 시작하는 내가 되길 원한다..