Search code examples
google-sheetsspreadsheetgoogle-appsgoogle-sheets-query

IF statement in query


I have a table with two columns A and B the first is a tag and the second is an amount. I am trying to write a query with two columns, one summing up negative values while the other summing up positive ones.

Coming from SQL, I tried the following

=QUERY(A1:B100, 
      "SELECT A, SUM( B * IF(B>0, 0, 1) ), 
                 SUM( B * IF(B<0, 0, 1) ) GROUP BY A ")

But it seems that the IF function is not supported in a query. I know I can create two intermediate columns in my sheet (one for positive value and one for negative ones), but I was wondering if it's possible to achieve what I want with a query or somehow without intermediate columns.


Solution

  • If you must use the query function, assuming your Tag Data is in Column A, and your Values in Column B:

    =arrayformula(query({A1:A100,if(B1:B100>0,B1:B100,),if(B1:B100<0,B1:B100,)},"Select Col1, sum(Col2), sum(Col3) where Col1 <>'' group by Col1 label Col1 'Tag', sum(Col2) 'Positive', sum(Col3) 'Negative'"))
    

    Here's the example output: https://docs.google.com/spreadsheets/d/1DW5CyPCC71CopW48uKy6basn-WP4hMfh7kuuJXT-C4o/edit#gid=1606239479