Click to See Complete Forum and Search --> : [RESOLVED] Can aggregate functions be run on a subset of a group?


svidgen
06-30-2009, 02:35 PM
Hello all,

Assuming MySQL (5.x) ...

I'm under the impression that aggregate functions cannot be run against a subset of a group. For example, suppose I would like to do something like this:

select
sum(b.total where b.some_field='A') total_A,
sum(b.total where b.some_field='B') total_B
from
some_table a
left join
some_table b using (misc_column)
group by
a.some_id;

To the best of my knowledge, the above isn't proper SQL/MySQL.

Am I stuck using subqueries and/or [inline] temporary tables? Or, is there a more "proper" (built-in) way to do this in MySQL?

The idea is to avoid implicitly building multiple in-memory tables and/or running subqueries to rebuild groups for analysis.

Thanks!

svidgen
06-30-2009, 02:46 PM
Solution found. Something along the lines of ...
select
sum(if(b.some_field='A',b.total,0)) total_A,
sum(if(b.some_field='B',b.total,0)) total_B
from
some_table a
left join
some_table b using (misc_column)
group by
a.some_id;
Idiotic simplicity ...