Hello,

I have data like this.

```
{
"mybucket": {
"timecode": 1,
"type": "test2",
"val": 1
}
},
{
"mybucket": {
"timecode": 2,
"type": "test2",
"val": 1
}
},
{
"mybucket": {
"timecode": 3,
"type": "test2",
"val": 1
}
},
{
"mybucket": {
"timecode": 4,
"type": "test2",
"val": 2
}
},
{
"mybucket": {
"timecode": 5,
"type": "test2",
"val": 2
}
},
{
"mybucket": {
"timecode": 6,
"type": "test2",
"val": 1
}
},
{
"mycket": {
"timecode": 7,
"type": "test2",
"val": 1
}
```

I want to construct N1QL query which returns the following data:

{

“mybucket”: {

“timecode”: 1,

“type”: “test2”,

“val”: 1

}

},

{

“mybucket”: {

“timecode”: 4,

“type”: “test2”,

“val”: 2

}

},

{

“mybucket”: {

“timecode”: 6,

“type”: “test2”,

“val”: 1

}

},

Basically, I need to separate the array of documents into parts with continuous value for “val” and then select the first document (ordered by timecode) from each part.

In SQL I would probably use some combination of window functions. How would I do this in N1QL? I started with trying to select previous value for “val” to know if it changed compared to previous row and go from there with this query:

```
SELECT
e1,
(SELECT e2.timecode AS prev_timecode FROM mybucket e2 USE KEYS META(e1).id WHERE e2.timecode < e1.timecode ORDER BY e2.timecode DESC LIMIT 1) x
FROM
mybucket e1
WHERE
e1.type="test2"
ORDER BY
e1.timecode
```

But it returns empty results for x.

Can you help me with how to approach this problem using N1QL? Thank you