您需要使用sum() over(order by time rows between preceding 4 and current row)的窗口功能。
SELECT
merchantName,
merchantID,
shipmentday,
listing_count,
sum(shipmentday * listing_count) over(order by period rows between preceding 4 and current row) / sum(listing_count) over(order by period rows between preceding 4 and current row) as weighed_ma
FROM (
SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS period
FROM your_table
);
注意:如果数据中有时间列,则可以忽略子查询。我正在生成period,因为您的示例中没有时间列。
如果窗口函数抛出错误,那么我假设您的 Hive 版本不支持所需的窗口函数。或者,您可以使用CROSS JOIN。 CROSS JOIN 将原始表中的所有行映射到目标表中的所有行(将其视为没有任何键匹配的左连接)。
WITH a AS (
SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS period
FROM your_table
)
SELECT
merchantName,
merchantID,
shipmentday,
listing_count,
sum(shipmentday_b * listing_count_b) / sum(listing_count_b) AS weighted_ma
FROM (
SELECT
a.*,
b.shipmentday AS shipmentday_b,
b.listing_count AS listing_count_b
FROM a
CROSS JOIN a AS b
WHERE b.rn BETWEEN a.rn - 4 and a.rn
) a
GROUP BY merchantName, merchantID, shipmentday,listing_count;