Search code examples
arraysgoogle-sheetsgoogle-sheets-formulaarray-formulasgoogle-query-language

Add column with sheet name of origin to merged sheet


Having this formula to merge and then filter by date, ranges from different sheets into a master sheet :

=QUERY({'Class 1'!A3:I14;'Class 2'!A3:I14}
,"SELECT Col1, Col3, Col4, Col5, Col6, Col7, Col8, Col9 WHERE (Col1 >= date '" & TEXT(TODAY(),"yyyy-MM-dd") & "' AND Col1 <= date '" & TEXT(TODAY()+9,"yyyy-MM-dd") & "')", FALSE)

The formula works like this: Grabs ranges from Class 1 and Class 2 sheets. Then it filters the results in the first column between today and 9 days from now. For each filtered result everything on the right from the third column till the ninth column is then displayed.

In the Master sheet I need to add a column containing the class (aka the name of the sheet of origin of each result) so is possible to understand from which class the students to be tested are from.

Sheet of example


Solution

  • Use IF and ARRAYFORMULA to add the class name for the first sheet and apply the same patter for the second sheet.

    A very rough way to apply the above:

    =ArrayFormula(QUERY({
    'Class 1'!A3:I14,IF(N('Class 1'!A3:I14),"Class 1");
    'Class 2'!A3:I14,IF(N('Class 2'!A3:I14),"Class 2")
    },"SELECT Col1, Col10, Col3, Col4, Col5, Col6, Col7, Col8, Col9 WHERE (Col1 >= date '" & TEXT(TODAY(),"yyyy-MM-dd") & "' AND Col1 <= date '" & TEXT(TODAY()+9,"yyyy-MM-dd") & "')", FALSE))
    

    N returns a number otherwise retuns nothing. It works in the above formula because the first column contains dates which Google Sheets handle them as serial numbers.

    Please note that the SELECT clause was also modified, it shows Col10 as the second column.