想到的第一种方法是使用row_number()
注释表,然后按 16 行的块分组。
SELECT min(id) as first_id, max(id) AS last_id, avg(rainfall) AS avg_this_16
FROM (
SELECT id, rainfall, row_number() OVER (order by id) AS n
FROM the_table
) x(id,rainfall,n)
GROUP BY n/16
ORDER BY n/16;
请注意,这不一定包括最后一组的 16 个样本。
或者,您可以通过用作窗口函数来计算运行平均值:avg()
SELECT id, avg(rainfall) OVER (ORDER BY id ROWS 15 PRECEDING)
FROM the_table;
...可能用行号注释它并选择你想要的:
SELECT id AS greatest_id_in_group, avg_last_16_inclusive FROM (
SELECT
id,
avg(rainfall) OVER (ORDER BY id ROWS 15 PRECEDING) AS avg_last_16_inclusive,
row_number() OVER (ORDER BY id) AS n
FROM the_table
) x WHERE n % 16 = 0;
这将忽略最后的 n<16 个样本,而不是为它们返回一行。
请注意,我假设不保证 ID 是连续的。如果它们没有间隙,则group by id/16
可以避免使用窗口功能。