M5-010Medium窗口函数 · Window functions🔥 大厂高频出现 1 次
如何计算 7 日移动平均?日期有缺失时怎么办?
How do you compute a 7-day moving average, and what if dates are missing?
💡 考场高分一句话答案:
先用日期骨架补齐(GENERATE_DATE_ARRAY + LEFT JOIN),再用 ROWS BETWEEN 6 PRECEDING 做移动平均。
Build a date spine first (GENERATE_DATE_ARRAY plus LEFT JOIN), then use ROWS BETWEEN 6 PRECEDING for the rolling window.
📌 核心考察要点 (Key Points)
- 缺失日期:ROWS 窗口按物理行,缺一天会变成“最近 7 条记录”而不是“最近 7 天”
- 补齐:生成日期序列 LEFT JOIN 实际数据,缺失填 0 或 NULL
- RANGE vs ROWS:RANGE 按值范围,配合日期可用,但跨类型时不直观
- 首尾:前 6 天窗口不满,通常仍计算(样本少)或标 NULL
- The bug: a ROWS window counts physical rows, so a missing day turns 'last 7 days' into 'last 7 records'
- Fix: generate the date series and LEFT JOIN the data, filling missing days with 0 or NULL
- RANGE vs ROWS: RANGE works on value ranges, which is less intuitive with dates
- Edges: the first six days have an incomplete window — compute anyway or return NULL, but decide explicitly
🔍 大厂面试官连环追问 (Follow-ups)
- 缺失日期该填 0 还是 NULL?对移动平均有什么影响?
- 如何做加权移动平均?
🎯 关联大厂考题实战训练 (1 题)
嫌字多看太累?进入苏格拉底式对话推演实验室
零打字负担,以大厂考官真实困境切入,通过点选直觉选项暴露思维盲区,手把手推导 Why。
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.