실무 · CH12
UTC로 하루를 자르면 일별 광고비가 최대 38.2% 어긋납니다
광고팀 데이터 직군의 첫 업무는 대개 "매체별 숫자를 매일 한 표로"입니다. 시간대, VAT, 중복 주문, UTM이 엇갈려 같은 날 같은 매체의 숫자가 리포트마다 다릅니다. 가상 원본 세 개를 DuckDB로 표준 테이블 하나로 만듭니다.
목표 테이블
| 열 | 뜻 | 규칙 |
|---|---|---|
| d | 날짜 | 한국 시간(KST) 기준 |
| ch | 채널 | UTM 정리 목록(meta, naver, …) |
| cost | 광고비 | VAT 제외로 통일 |
| clicks | 클릭 | 매체 보고 그대로 |
| orders, rev | 주문·매출 | 우리 주문 DB, 중복 제거 후 마지막 UTM 기준 |
| roas | rev ÷ cost | 이 표의 기준으로만 계산 |
가상 데이터 매체 A는 시간 단위·UTC·VAT 제외, 매체 B는 일 단위·KST·VAT 포함, 주문 원본에는 픽셀이 두 번 쏜 중복 주문과 제각각인 utm_source가 들어 있습니다.
# 12 광고 데이터 파이프라인: 매체별 원본을 한 표로 (DuckDB, 가상 원본 데이터)
import duckdb, numpy as np, pandas as pd
from common import save
rng = np.random.default_rng(12)
days = pd.date_range('2026-11-01', periods=14, freq='D')
# 매체 A: 시간대 UTC, 시간 단위 행, 비용 VAT 제외
ha = pd.date_range('2026-10-31 15:00', periods=14 * 24, freq='h') # = KST 11/01 00시 ~ 11/14 23시
kst_hour = (ha + pd.Timedelta(hours=9)).hour
a = pd.DataFrame({'hour_utc': ha, 'campaign': 'A_prospect', 'spend': (rng.gamma(2, 4000, len(ha)) * (1 + 1.5 * np.isin(kst_hour, range(19, 24)))).round(),
'clicks': rng.poisson(40, len(ha))})
# 매체 B: 시간대 KST, 일 단위, 비용 VAT 포함
b = pd.DataFrame({'day_kst': days, 'campaign': 'B_search', 'cost_vat': (rng.normal(220000, 30000, 14) * 1.1).round(), 'clicks': rng.poisson(900, 14)})
# 주문: KST, 픽셀이 두 번 쏜 중복 주문 포함
n = 1500
o = pd.DataFrame({'order_id': np.arange(n), 'ts_kst': pd.Timestamp('2026-11-01') + pd.to_timedelta(rng.uniform(0, 14 * 24, n), unit='h'),
'amount': rng.gamma(3, 12000, n).round(-2),
'utm_source': rng.choice(['facebook', 'fb', 'Meta', 'naver', 'naver_sa', 'NAVER', None], n, p=[.2, .1, .1, .2, .1, .1, .2])})
dup = o.sample(60, random_state=1)
o = pd.concat([o, dup]).sort_values('ts_kst')
con = duckdb.connect()
for name, df in [('raw_a', a), ('raw_b', b), ('raw_orders', o)]: con.register(name, df)
# 함정 1: UTC 날짜로 묶으면 하루 경계가 9시간 어긋난다
cmp = con.sql("""
select cast(hour_utc as date) d_utc, sum(spend) s from raw_a group by 1 order by 1
""").df()
cmp2 = con.sql("""select cast(hour_utc + interval 9 hour as date) d_kst, sum(spend) s from raw_a group by 1 order by 1""").df()
m = cmp.merge(cmp2, left_on='d_utc', right_on='d_kst', how='inner', suffixes=('_utc', '_kst'))
m['diff_pct'] = (m.s_utc / m.s_kst - 1) * 100
print('매체 A 일별 비용: UTC 날짜 vs KST 날짜 (처음 5일)')
print(m.head(5).to_string(index=False))
print(f'하루 차이 절댓값 평균 {m.diff_pct.abs().mean():.1f}%, 최대 {m.diff_pct.abs().max():.1f}%')
# 함정 2: VAT
vat_gap = b.cost_vat.sum() - b.cost_vat.sum() / 1.1
print(f'매체 B 14일 비용: VAT 포함 {b.cost_vat.sum():,.0f}원, 제외 {b.cost_vat.sum()/1.1:,.0f}원 (차이 {vat_gap:,.0f}원)')
# 함정 3: 중복 주문
dups = con.sql("select count(*) - count(distinct order_id) from raw_orders").fetchall()[0][0]
print(f'주문 원본 {len(o):,}행 중 중복 {dups}행')
# 표준 일별 테이블
fact = con.sql("""
with a as (select cast(hour_utc + interval 9 hour as date) d, 'meta' ch, sum(spend) cost, sum(clicks) clicks from raw_a group by 1),
b as (select cast(day_kst as date) d, 'naver' ch, round(sum(cost_vat)/1.1) cost, sum(clicks) clicks from raw_b group by 1),
o as (select distinct order_id, cast(ts_kst as date) d, amount,
case lower(coalesce(utm_source,'')) when 'facebook' then 'meta' when 'fb' then 'meta' when 'meta' then 'meta'
when 'naver' then 'naver' when 'naver_sa' then 'naver' else '(none)' end ch from raw_orders),
od as (select d, ch, count(*) orders, sum(amount) rev from o group by 1,2)
select x.d, x.ch, x.cost, x.clicks, coalesce(od.orders,0) orders, coalesce(od.rev,0) rev, round(coalesce(od.rev,0)/x.cost*100) roas
from (select * from a union all select * from b) x left join od using (d, ch) order by 1,2
""").df()
fact.to_csv('out/fact_ad_daily.csv', index=False)
print('\n표준 테이블 fact_ad_daily (앞 6행)'); print(fact.head(6).to_string(index=False))
summ = fact.groupby('ch')[['cost', 'orders', 'rev']].sum(); summ['roas'] = (summ.rev / summ.cost * 100).round()
print('\n14일 합계'); print(summ.to_string())
none = con.sql("select count(distinct order_id) from raw_orders where utm_source is null").fetchall()[0][0]
print(f'utm 없는 주문 {none}건은 어느 매체에도 붙지 않는다')
save('pipe', dict(diff_mean=round(m.diff_pct.abs().mean(), 1), diff_max=round(m.diff_pct.abs().max(), 1), vat_gap=round(vat_gap), dups=int(dups),
rows=len(o), none=int(none), summ={k: [int(v['cost']), int(v['orders']), int(v['rev']), int(v['roas'])] for k, v in summ.iterrows()}))$ python 12_pipeline.py
매체 A 일별 비용: UTC 날짜 vs KST 날짜 (처음 5일)
d_utc s_utc d_kst s_kst diff_pct
2026-11-01 268066.0 2026-11-01 252112.0 6.328140
2026-11-02 254226.0 2026-11-02 281638.0 -9.733062
2026-11-03 236687.0 2026-11-03 243373.0 -2.747223
2026-11-04 231292.0 2026-11-04 202600.0 14.161895
2026-11-05 285509.0 2026-11-05 296527.0 -3.715682
하루 차이 절댓값 평균 8.7%, 최대 38.2%
매체 B 14일 비용: VAT 포함 3,129,062원, 제외 2,844,602원 (차이 284,460원)
주문 원본 1,560행 중 중복 60행
표준 테이블 fact_ad_daily (앞 6행)
d ch cost clicks orders rev roas
2026-11-01 meta 252112.0 1015.0 35 1305300.0 518.0
2026-11-01 naver 206865.0 889.0 46 1567200.0 758.0
2026-11-02 meta 281638.0 948.0 42 1460700.0 519.0
2026-11-02 naver 221153.0 904.0 35 1350100.0 610.0
2026-11-03 meta 243373.0 945.0 38 1441000.0 592.0
2026-11-03 naver 185238.0 889.0 47 1813900.0 979.0
14일 합계
cost orders rev roas
ch
meta 3550957.0 590 21211500.0 597.0
naver 2844602.0 610 22397700.0 787.0
utm 없는 주문 300건은 어느 매체에도 붙지 않는다함정 세 개, 숫자로
| 함정 | 이번 데이터에서 | 고치는 법 |
|---|---|---|
| 시간대 | UTC 날짜와 KST 날짜로 묶은 일별 비용 차이 평균 8.7%, 최대 38.2% | 시간 단위로 받아 +9시간 한 뒤 날짜로 묶기. 일 단위만 주는 매체는 계정 시간대를 KST로 설정 |
| VAT | 매체 B 14일 비용에서 VAT 284,460원 차이 | 모든 비용을 VAT 제외로. 리포트 첫 줄에 기준 적기 |
| 중복 주문 | 주문 원본 1,560행 중 60행 중복 | order_id로 distinct |
| UTM 없음 | utm 없는 주문 300건 | 어느 매체에도 붙이지 않고 따로 보고(직접 방문·자연 검색일 수 있음) |
매일 아침 리포트 전 점검
- 어제 날짜 행이 매체마다 다 들어왔나(매체 API는 지연·수정이 흔합니다. 최근 3일은 다시 받아 덮어쓰세요).
- 매체 화면의 어제 비용과 표의 비용이 VAT 기준을 맞춘 뒤 같은가.
- 주문 DB 매출 합계와 표의 rev 합계 + UTM 없음 매출이 같은가.
- ROAS가 갑자기 2배가 된 날은 비용이 빠졌는지부터 의심.
함정
매체 화면에서 엑셀로 복사해 붙이기
복사하는 날마다 시간대·VAT·기여 설정이 화면 기본값을 따라가 숫자가 바뀝니다. API나 내보내기 파일을 같은 설정으로 받아 코드로 묶으세요.
이것만 기억하세요
표준 테이블의 규칙 세 줄: 날짜는 KST, 비용은 VAT 제외, 매출은 우리 주문 DB. 이 세 줄을 모든 리포트 머리에 적으세요.