I have sql query like this:
select a.x, a.y, sum(a.foo) as foo_sum
from a
group by a.x
and after running this query, I can access to foo_sum.
I want to do something like this:
select a.x, a.y, sum(a.foo) as foo_sum
from a
group by a.x
union
select a.x, a.y, sum(a.bar) as bar_sum
from a
group by a.y
but after running this one, my program dosent know foo_sum, anybody knows why?
thank you.
Edit: I want to have 4 column x, y, foo_sum and bar_sum, is this possible?
I don’t think this is possible, because your number of unique
xvalues might not be the same as the number of uniqueyvalues.For example, suppose
awas like this:The first query (
foo_sum GROUP BY x) would give:The second (
bar_sum GROUP BY y) gives:How can you mash the
bar_sumcolumn on the end of thefoo_sumtable? There is no correspondingfoo_sumvalue for (x,y)=(2,3), but there is a correspondingbar_sum.The best you could achieve would be something like this:
To achieve this the only way I can think of is using a
FULL OUTER JOIN. Note that doingSELECT x, y, SUM(foo), SUM(bar) FROM a GROUP BY x,ywon’t give the same results as it groups differently.This makes sure all the
x,ycombinations from each table is inserted, even if there are no correspondingx,yin the other table.However MySQL has no
FULL OUTER JOIN, and you have to simulate aA FULL OUTER JOIN BbyUNIONing aLEFTandRIGHTjoin together:In your case this translates to the very ugly:
This is highly inefficient ! I suggest you instead do the grouping on the PHP side (or whatever other language you are using with MySQL) than the SQL side.
Who knows, there may be a more efficient way to do this since all you want is
SUMs – there could be a clever way to group and sum to achieve your effect.