FormulaCraft

How to use QUERY for conditional aggregation in Excel and Google Sheets

Topic:QUERY (Google Sheets SQL)

Heads up: Excel and Google Sheets do this differently.

Excel
=SUMIFS(C2:C10,B2:B10,"Paid",D2:D10,E2)
Google Sheets
=QUERY(A1:D10,"SELECT D, SUM(C) WHERE B = 'Paid' GROUP BY D LABEL SUM(C) 'Paid Revenue'",1)

Try it with your data

Edit the grid or formula, then run it through a real spreadsheet engine — no signup.

Sample data — click any cell to edit

Runs server-side · free · no signup

Step by step

  1. 1Set up your data with columns: Order ID (A), Status (B), Amount (C), Region (D) with headers in row 1.
  2. 2To get total paid revenue grouped by region: =QUERY(A1:D10,"SELECT D, SUM(C) WHERE B = 'Paid' GROUP BY D LABEL SUM(C) 'Paid Revenue'",1).
  3. 3The WHERE clause applies the condition (Status = 'Paid') before aggregation — so only qualifying rows contribute to SUM(C).
  4. 4Add multiple aggregations in one formula: "SELECT D, SUM(C), COUNT(A), AVG(C) WHERE B = 'Paid' GROUP BY D LABEL SUM(C) 'Total', COUNT(A) 'Orders', AVG(C) 'Avg Order'".
  5. 5To filter by multiple conditions, combine with AND: WHERE B = 'Paid' AND C > 500 excludes small orders before summing.

Tips

Need the Google Sheets version instead? Open Sheets variant in workspace →

Working on a sheet you inherited? Run the Auditor on the whole file first — it flags every #REF!, #N/A, broken column pattern, and inconsistent formula in seconds, free, no signup.

Frequently asked

Can I filter on the aggregated result (equivalent to SQL HAVING)?

Not directly — QUERY does not support a HAVING clause. The workaround is to wrap the QUERY in another QUERY: =QUERY(QUERY(A1:D10,"SELECT D, SUM(C) WHERE B = 'Paid' GROUP BY D",1),"SELECT * WHERE Col2 > 1000",1) where the outer QUERY filters on the aggregated column.

How do I count distinct values inside a group?

Use COUNT on a column you know has unique values per row (like an order ID column A): SELECT D, COUNT(A) WHERE B = 'Paid' GROUP BY D. This gives the number of paid orders per region.

Is conditional aggregation faster in QUERY or SUMIFS?

For a single criterion SUMIFS is faster to calculate. QUERY with GROUP BY becomes more practical when you need multiple aggregations or dynamic output — it spills a full summary table instead of requiring one SUMIFS formula per cell.

More on QUERY (Google Sheets SQL)

See all →

Formulas used

Related tasks

Written and reviewed by FormulaCraft Team. Each formula on this page is run through our verification engine before publishing.

Last reviewed: