简体   繁体   中英

SQL function to group consecutive rows

I have a case that was originally done in excel that I'm trying to replicate in a query. I have data structured as follows:

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

I need a function that can group by/agg by consecutive 3 rows such that I return with:

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

Use the LEAD() function, as in:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM