I have a table serving as a transaction log:
Date Action Qty
11-23 ADD 1
11-23 REMOVE 2
11-23 ADD 3
I would like a query to aggregate all of ADDs and all of the REMOVEs separately for a given date.
Each of these select statements work fine, but they cannot be joined:
select date, sum(qty) as Added from table where action='Add' and date='11-23'
natural join
select date, sum(qty) as Removed from table where action='Remove' and date='11-23'
Can I store the results of each select statement to a table and then join those? Is there a way to avoid this all together?
Thanks-
Jonathan
Take a look at UNION syntax, if you really want to add the result sets of multiple queries into one:
http://dev.mysql.com/doc/refman/5.0/en/union.html
However, in this case, take a look at GROUP BY
You could group on
Date, Actiontherefore resulting in one record per day per action, withSUM()being able to give you the quantity.For example:
Will result in: