简体   繁体   中英

Query function in Google Sheets - Get non-empty last cell in a column depending on another column

I'd need to retrieve the last non-empty cell in a column based on changes on the adjacent column.

In the example below, the yellow cells are my target. They are defined by a change in column A.

click here to see example

I already managed to do this with normal functions as seen in the picture:

=INDEX(ArrayFormula(FILTER(B2:B20,A2:A20=D2)),ArrayFormula(MATCH(0, FILTER(B2:B20,A2:A20=D2),-1)),1)

I need now to do it with query function as the results must automatically update as an importrange grows.

So far this works - but I still would need to create proper dependancy on column A:

=QUERY(A2:B20, "select A, B where B is not null limit 1 offset "&(COUNT(A2:B20)-1))

like so: click here to see example

Thank you in advance for any suggestions!

PS: Using solution provided by Player0 to my real data here: click here I cannot get to "unsort" by the first column, setting sort_column to 0 does not work. Basically I need to keep the order of elements in column A the same at all times - and apparently SORTN cannot do it.

To apply it to the main example - if column A was made of a,c,d,b (instead of a,b,c,d) I would have to keep it as such.

use:

=SORTN(QUERY(SORT(A2:B, ROW(A2:A), 0), 
 "where Col2 is not null"), 9^9, 2, 1, 1)

在此处输入图片说明


update:

=ARRAY_CONSTRAIN(SORT(SORTN(QUERY(SORT({A2:B, ROW(A2:A)}, ROW(A2:A), 0), 
 "where Col2 is not null"), 9^9, 2, 1, 1), 3, 1), 9^9, 2)

在此处输入图片说明

Your task can be accomplished in two steps:

  1. determine the rows that contain the desired data =index(query({A2:B20,ROW(A2:B20)},"select max(Col3) where Col2 is not null group by Col1 label max(Col3)''")) and assemble the result to a regular expression using formula JOIN("|", -- query result --)在此处输入图片说明 the result we have a string: 5|11|14|19
  1. use a new query to output the values from the previously found rows =index(query({A2:B20,ROW(A2:B20)},"select Col1,Col2 where Col3 matches '"& join("|",query({A2:B20,ROW(A2:B20)},"select max(Col3) where Col2 is not null group by Col1 label max(Col3)''")) &"'")) 在此处输入图片说明

the range A2:B20 is used for the example, but the formula also works with the open range A2:B

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