SQL函数对连续行进行分组

时间:2019-01-22 17:16:33

标签: sql tsql

我有一个案例最初是在excel中完成的,我试图在查询中进行复制。我的数据结构如下:

Field1 | Field2
---------------
1      |5
2      |10
3      |5
4      |10
5      |5

我需要一个可以按连续3行进行分组/汇总的函数,以便返回:

Field1 | Field2
---------------
123    |20
234    |25
345    |20

1 个答案:

答案 0 :(得分:1)

使用LEAD()函数,如下所示:

with
x as (
  select
    field1 as x1,
    lead(field1) as x2,
    lead(field1, 2) as x3,
    field2 as y1,
    lead(field2) as y2,
    lead(field2, 2) as y3
  from my_table
)
select
  x1 + x2 + x3 as field1,
  y1 + y2 + y3 as field2
from x
where x1 is not null
  and x2 is not null
  and x3 is not null