PostgreSQL 窗口函数计算每个间隔的总和

问题描述 投票:0回答:1

该表由以下脚本表示:

CREATE TABLE sales (
  id SERIAL PRIMARY KEY,
  product_id INTEGER,
  sales_date DATE,
  quantity INTEGER,
  price NUMERIC
);

INSERT INTO sales (product_id, sales_date, quantity, price) VALUES
   (1, '2023-01-01', 10, 10.00),
   (1, '2023-01-02', 12, 12.00),
   (1, '2023-01-03', 15, 15.00),
   (2, '2023-01-01', 8, 8.00),
   (2, '2023-01-02', 10, 10.00),
   (2, '2023-01-03', 12, 12.00);

任务是计算每个product_id最近3天的销售数量。

通过在子查询中使用窗口函数应用此查询:

select product_id, max(increasing_sum) as quantity_last_3_days
   from 
        (SELECT product_id,
         SUM(quantity) OVER (PARTITION BY product_id ORDER BY sales_date RANGE BETWEEN INTERVAL '2 days'
                PRECEDING AND CURRENT ROW) AS increasing_sum
         FROM sales) as s
   group by product_id;

我收到了预期的输出:

  | product_id | quantity_last_3_days |
  |____________|______________________|            
  |_____1______|___________37_________|
  |_____2______|___________30_________|     
 

但是这个解决方案是最优的吗?有没有办法通过使用不带子查询的窗口函数来解决这个问题?

sql postgresql window-functions
1个回答
0
投票

这看起来是一个复杂的查询。据我所知,这就足够了:

select product_id, sum(quantity) as quantity_last_3_days
from sales
where sales_date > (now() - interval '72 hours')
group by product_id;
© www.soinside.com 2019 - 2024. All rights reserved.