Break out sum on condition

from the Artful Common Queries page


To obtain part sums of a column based on specific conditions, use If() or CASE, eg ...
select 
  sum( if(condition1, col, 0) ) as cond1,
  sum( if(condition2, col, 0) ) as cond2,
  ...etc... 
from tbl;
It's also called crosstabbing or pivoting. The pivot is on the expression that conditions the aggregating function. Pito Salas invented the method while he was developing spreadsheet software for Lotus Corp. For more on the topic see the "Crosstabs (Pivot tables)" heading here.

Last updated 25 Jan 2025