You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整SQL窗口函数RANGE区间?排除上月同期首日统计数据

调整SQL窗口函数日期范围实现指定区间统计

原SQL语句使用range between interval '1' month preceding and current row,当value_day = Aug 21时会包含7月21日至8月21日的数据。要改为统计7月22日至8月21日的总和,只需将起始区间向后偏移1天,具体调整如下:

调整后的SQL语句

sum(purchases) over(
    partition by category 
    order by value_day 
    range between interval '1' month preceding + interval '1' day and current row
)

原理说明

通过在interval '1' month preceding的基础上加上interval '1' day,当value_day = Aug 21时,起始日期就从原来的7月21日变为7月22日,正好覆盖目标区间,排除了7月21日的记录。

如果是MySQL等不支持直接interval相加的数据库,可以改用日期函数实现:

sum(purchases) over(
    partition by category 
    order by value_day 
    range between date_add(date_sub(value_day, interval 1 month), interval 1 day) and current row
)

内容的提问来源于stack exchange,提问作者LetterOne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:27:17