2

I have a query where the output involves summing two columns. If either of the columns never has a value (given a set of filter criteria in the where clause), there is no result. Why?

Here is an example sheet.

=QUERY(A2:C,"select sum(B) where A = 'ard'",0) -> result exists

=QUERY(A2:C,"select sum(C) where A = 'ard'",0) -> no result

=QUERY(A2:C,"select sum(B) - sum(C) where A = 'ard'",0) -> no result

1 Answer 1

4

You are used to an empty cell having a value of zero in other functions. However, QUERY acts uniquely from other functions. As currently set up, you are asking QUERY to subtract a null string from a number (i.e., to act on two different data types), and QUERY makes no assumptions about what those "should mean" (i.e., it is literal). This is the same reason QUERY only returns one data type (the most populous one) per column if there are mixed data types in that column.

One approach would be to pre-process the range and then use Colx notation:

=ArrayFormula(QUERY({A2:A,IF(B2:C="",0,B2:C)},"select sum(Col2) - sum(Col3) where Col1 = 'ard'",0))

However, you'd be better of just using a function that does make the assumption that null means zero:

=SUM(FILTER(B2:B-C2:C,A2:A="ard"))

2
  • For what it's worth, the filter suggestion at the bottom doesn't work because I'm looking for a single result that sums up all of the cells, whereas filter produces one result per filtered row. The arrayformula suggestion likely works, though (haven't check it yet). Thanks! Apr 28, 2021 at 20:27
  • 1
    Simple fix on the FILTER formula. See my updated formula above, which is simply wrapped in SUM( ).
    – Erik Tyler
    Apr 28, 2021 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.