I have the following query that UNION
two tables and retrieves the SUM
of some fields and other information as you can see:
SELECT SUM(a.quantity_input) AS `quantity_input`,
SUM(a.quantity_output) AS `quantity_output`,
a.average_cost_price,
a.item_reference,
a.item_description
FROM ((SELECT SUM(aco.quantity_input) AS `quantity_input`,
SUM(aco.quantity_output) AS `quantity_output`,
aco.average_cost_price,
item.reference AS `item_reference`,
item.description AS `item_description`
FROM stock_accumulated AS aco
INNER JOIN items AS item ON item.id = aco.item_id
WHERE aco.year = '2016' AND
aco.month < '03'
GROUP BY item.reference)
UNION ALL
(SELECT Sum(mov.quantity_input) AS `input_quantity`,
Sum(mov.quantity_output) AS `quantity_output`,
mov.average_cost_price,
item.reference AS `item_reference`,
item.description AS `item_description`
FROM stock_movements AS mov
INNER JOIN items AS item ON item.id = mov.item_id
WHERE mov.movement_date <= '2016-03-31' AND
mov.movement_date >= '2016-03-01'
GROUP BY item.reference)) a
GROUP BY a.item_reference
My only problem (at least so far) with this query is that I need to retrieve the average_cost_price
of the last row in my second table.
You can try the following query in SQLFiddle and see the image below to understand what I'm referring to.