下面是一个使用标准SQL中带有时间约束的窗口的示例代码:
-- 创建测试表
CREATE TABLE orders (
order_id INT,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10, 2)
);
-- 插入测试数据
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES
(1, 1, '2022-01-01', 100),
(2, 2, '2022-01-01', 200),
(3, 1, '2022-01-02', 150),
(4, 2, '2022-01-02', 300),
(5, 1, '2022-01-03', 200),
(6, 2, '2022-01-03', 250);
-- 查询每个客户在过去3天内的订单总金额
SELECT
customer_id,
order_date,
total_amount,
SUM(total_amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
RANGE BETWEEN INTERVAL '3' DAY PRECEDING AND CURRENT ROW
) AS total_amount_3_days
FROM orders
ORDER BY customer_id, order_date;
上述示例代码中,我们创建了一个名为orders
的测试表,并插入了一些测试数据。然后,我们使用标准SQL中的窗口函数来查询每个客户在过去3天内的订单总金额。
在窗口函数中,我们使用PARTITION BY
子句将数据按照customer_id
进行分组,然后使用ORDER BY
子句按照order_date
进行排序。接着,我们使用RANGE BETWEEN INTERVAL '3' DAY PRECEDING AND CURRENT ROW
子句来定义窗口的范围,即过去3天内的数据。
最后,我们将窗口函数的结果命名为total_amount_3_days
,并将其包含在查询结果中。
运行以上代码,将会得到如下结果:
customer_id | order_date | total_amount | total_amount_3_days
--------------------------------------------------------------
1 | 2022-01-01 | 100 | 100
1 | 2022-01-02 | 150 | 250
1 | 2022-01-03 | 200 | 450
2 | 2022-01-01 | 200 | 200
2 | 2022-01-02 | 300 | 500
2 | 2022-01-03 | 250 | 750
以上结果显示了每个客户在过去3天内的订单总金额。