sql 查询中的分区,仅选择前一行而不选择当前行

Partition in a sql query, selecting only previous rows without the current one

假设我有下一个 table(销售额),其中包含某个城市在特定月份的销售额信息:

月 7 8 9 10

城市a 10 20 30 40

如果我决定执行下一个查询:

select city, month, 
avg(sales) over (partition by city order by month rows 2 preceding) as avg
from sales

我会有下一个结果

月 7 8 9 10

城市a 10 20 30 40

平均 10 10 20 30

此查询将使用前 2 个月和当前月份,但我希望只计算前两个月而不计算当前月份,如下所示:

平均 10 10 15 25

有办法吗?

。有办法吗?

应该是这个

select city, month, 
avg(sales) over (partition by city order by month rows between 2 preceding and 1 preceding) as avg
from sales

或者您甚至可以使用 INTERVAL 而不是物理行。

select city, month, 
avg(sales) over (partition by city order by month RANGE between NUMTOYMINTERVAL(2,'MONTH') preceding and NUMTOYMINTERVAL(1,'MONTH') preceding) as avg
from sales