Search code examples
sortinggoogle-sheetsarray-formulasgoogle-sheets-querygs-vlookup

retrieve only unique values via query


Here's the formula I currently use:

=query(IMPORTRANGE("XXXX","XXXXX!A:H"), 
"select Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8 
 where Col1> date '"&TEXT(F1,"yyyy-mm-dd")&"' and Col3 = '"&B1&"' and Col4 = '"&D1&"'
 order by Col1 desc",1)

The formula is working. Col1 includes input dates. I retrieve only values that are after a date listed in F1. Col3 and Col3 include some properties which are selected in cells B1 and D1, accordingly. Col5 includes strings (client names). client name can repeat on several rows. I'd like to retrieve just the most recent one. Any ideas on how to do it?

And, to add more fun into the question, would it be the same idea to retrieve the oldest row per client?


Here's a link to demo sheet, details in the "unique query" tab.

Another challenge can be to retrieve X number of row per client, and not just the most recent one.


Solution

  • try:

    =SORTN(QUERY(IMPORTRANGE("1LoHg53hzQvYtOLTcDwxLY8OrKVN4F7usX8YI41BtdWg", "Activity list!A:E"), 
     "where Col1 > date '"&TEXT(I2, "yyyy-mm-dd")&"' 
        and Col2 = '"&I3&"' 
      order by Col1 desc", 1), 99^99, 2, 4, 1)
    

    enter image description here

    SORTN explained:
    
    99^99    all rows - no limits
    2        means "merge mode"
    4        collapse 4th column into unique values
    1        return 4th column ascending - 0 for descending