Search code examples
google-sheetsgoogle-sheets-formula

How can I get/query data from a table in Google Spreadsheets and limit to the first X rows for each "set" of rows?


I have data (example below) that represents multiple sets of data. I want to get all the sets but limit each set to the first X rows.

I know how to use the limit function of query but that seems to limit for all the rows.

Example Data

app ID app name l1 manager target score amount to drop by score dimension name dimension value weight
1 one a 49 10 1 35 3.50
1 one a 49 10 2 9 0.90
1 one a 49 10 3 15 1.50
2 two a 32 70 1 50 0.71
2 two a 32 70 2 22 0.31
2 two a 32 70 3 30 0.43
3 three a 46 67 1 45 0.67
3 three a 46 67 2 18 0.27
3 three a 46 67 3 50 0.75
4 four a 43 30 1 19 0.63
4 four a 43 30 2 41 1.37
4 four a 43 30 3 13 0.43
5 five b 38 17 1 1 0.06
5 five b 38 17 2 38 2.24
5 five b 38 17 3 16 0.94
6 six b 37 73 1 48 0.66
6 six b 37 73 2 38 0.52
6 six b 37 73 3 24 0.33
7 seven b 36 8 1 5 0.63
7 seven b 36 8 2 3 0.38
7 seven b 36 8 3 36 4.50
8 eight b 45 56 1 16 0.29
8 eight b 45 56 2 44 0.79
8 eight b 45 56 3 41 0.73
9 nine c 44 55 1 6 0.11
9 nine c 44 55 2 50 0.91
9 nine c 44 55 3 43 0.78
10 ten c 37 30 1 13 0.43
10 ten c 37 30 2 29 0.97
10 ten c 37 30 3 25 0.83

Each app ID is one set.

I can sort on app ID and dimension value like so: =QUERY(A14:H44, "SELECT * ORDER BY A, G").

In this example, I only want it to return the first 2 rows for each app ID/set. So the expected output would be like:

app ID app name l1 manager target score amount to drop by score dimension name dimension value weight
1 one a 49 10 2 9 0.90
1 one a 49 10 3 15 1.50
2 two a 32 70 2 22 0.31
2 two a 32 70 3 30 0.43
3 three a 46 67 2 18 0.27
3 three a 46 67 1 45 0.67
4 four a 43 30 3 13 0.43
4 four a 43 30 1 19 0.63
5 five b 38 17 1 1 0.06
5 five b 38 17 3 16 0.94
6 six b 37 73 3 24 0.33
6 six b 37 73 2 38 0.52
7 seven b 36 8 2 3 0.38
7 seven b 36 8 1 5 0.63
8 eight b 45 56 1 16 0.29
8 eight b 45 56 3 41 0.73
9 nine c 44 55 1 6 0.11
9 nine c 44 55 3 43 0.78
10 ten c 37 30 1 13 0.43
10 ten c 37 30 3 25 0.83

Solution

  • Here's one approach (not query-based) you may test out:

    =reduce(A1:H1,sort(unique(tocol(A2:A,1))),lambda(a,c,iferror(vstack(a,array_constrain(sort(filter(A:H,A:A=c),7,1),2,8)))))
    
    • array_constrain is used here to set the limit as 2 rows * 8 columns which you may change accordingly
    • sort is used to ascend both column_1 A & column_7 G

    enter image description here