SQL 移动 window 两级 groupby
SQL Moving window over two level of groupby
我有以下 table 个用户订单:
CREATE TABLE orders (
order_id UUID,
user_id UUID,
date date,
order_type integer
);
我想写 SQL 来执行以下操作:
- 对于每个订单,要计算用户在前一周(7 天)内的订单数量。
下面这样写,但是它统计的是每个用户的订单数,而不是两级groupby的订单数。
SELECT order_id, user_id,
COUNT(order_id) OVER(PARTITION BY user_id ORDER BY date ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) as num_orders_7days
FROM orders
您应该使用 RANGE
子句而不是 ROWS
并具有适当的日期间隔:
SELECT order_id, user_id, date,
COUNT(order_id) OVER (
PARTITION BY user_id
ORDER BY date
RANGE BETWEEN INTERVAL 7 day PRECEDING AND INTERVAL 1 day PRECEDING
) as num_orders_7days
FROM orders;
参见demo。
我有以下 table 个用户订单:
CREATE TABLE orders (
order_id UUID,
user_id UUID,
date date,
order_type integer
);
我想写 SQL 来执行以下操作:
- 对于每个订单,要计算用户在前一周(7 天)内的订单数量。
下面这样写,但是它统计的是每个用户的订单数,而不是两级groupby的订单数。
SELECT order_id, user_id,
COUNT(order_id) OVER(PARTITION BY user_id ORDER BY date ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) as num_orders_7days
FROM orders
您应该使用 RANGE
子句而不是 ROWS
并具有适当的日期间隔:
SELECT order_id, user_id, date,
COUNT(order_id) OVER (
PARTITION BY user_id
ORDER BY date
RANGE BETWEEN INTERVAL 7 day PRECEDING AND INTERVAL 1 day PRECEDING
) as num_orders_7days
FROM orders;
参见demo。