Вы можете использовать lead()
и sum()
. Предположим, что month
- это строка:
select concat(month, ',', lead(month) over (order by year, month), ',',
lead(month, 2) over (order by year, month)
),
sum(count) over (order by year, month rows between current row and 2 following) as total
from t;
Или:
with t as (
select 2017 as year, 1 as month, 3 as count union all
select 2017, 2, 4 union all
select 2017, 3, 2 union all
select 2017, 4, 1 union all
select 2017, 5, 5 union all
select 2017, 6, 6
)
select array_to_string(array_agg(cast(count as string)) over (order by year, month rows between current row and 2 following), ','),
sum(count) over (order by year, month rows between current row and 2 following)
from t;
Использование array_agg()
в качестве оконной функции, вероятно, немного более громоздко, чем lead()
. Однако для еще нескольких элементов было бы проще.