# getting the last 2 rows of each group

**URL:** <https://forum.kx.com/t/getting-the-last-2-rows-of-each-group/10331>\
**Category:** Community Support\
**Tags:** kdb-and-q\
**Created:** [August 31, 2015, 9:49am UTC](https://forum.kx.com/t/getting-the-last-2-rows-of-each-group/10331 "2015-08-31T09:49:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![effbiae](https://avatars.discourse-cdn.com/v4/letter/e/ecae2f/32.png) [@effbiae](https://forum.kx.com/u/effbiae)\
**Post date:** [August 31, 2015, 9:49am UTC](https://forum.kx.com/t/getting-the-last-2-rows-of-each-group/10331/1 "2015-08-31T09:49:00Z")

</div>

how do i go about getting the last two rows in a group?

q)show t:flip `a`b!(1 1 2 3 3 3;til 6);

a b

* * *

1 0

1 1

2 2

3 3

3 4

3 5

q)select[-2] by a from t

a| b

-| -

2| 2

3| 5

q)select b by a from t

a| b &nbsp; &nbsp;

-| -----

1| 0 1 &nbsp;

2| ,2 &nbsp;&nbsp;

3| 3 4 5

the result i’d like is:

a b

* * *

1 0

1 1

2 2

3 4

3 5

thanks,

jack

---

<div class="post-metadata">

**Author:** ![quintanar4011](https://avatars.discourse-cdn.com/v4/letter/q/6f9a4e/32.png) [@quintanar4011](https://forum.kx.com/u/quintanar4011)\
**Post date:** [August 31, 2015, 10:16am UTC](https://forum.kx.com/t/getting-the-last-2-rows-of-each-group/10331/2 "2015-08-31T10:16:00Z")

</div>

You may find idxs first:

t raze value&nbsp; exec 2 sublist i by a from t

WBR, Andrey Kozyrev.

???, 31 ??? 2015 ?., 11:49:43 UTC+3 ??? effbiae ???:

> how do i go about getting the last two rows in a group?
> 
> q)show t:flip `a`b!(1 1 2 3 3 3;til 6);
> 
> a b
> 
> * * *
> 
> 1 0
> 
> 1 1
> 
> 2 2
> 
> 3 3
> 
> 3 4
> 
> 3 5
> 
> q)select[-2] by a from t
> 
> a| b
> 
> -| -
> 
> 2| 2
> 
> 3| 5
> 
> q)select b by a from t
> 
> a| b &nbsp; &nbsp;
> 
> -| -----
> 
> 1| 0 1 &nbsp;
> 
> 2| ,2 &nbsp;&nbsp;
> 
> 3| 3 4 5
> 
> the result i’d like is:
> 
> a b
> 
> * * *
> 
> 1 0
> 
> 1 1
> 
> 2 2
> 
> 3 4
> 
> 3 5
> 
> thanks,
> 
> jack
