我有以下查詢UNION
兩個表並檢索某些字段和其他信息的SUM
,你可以看到:MySQL的UNION ALL - 值優先
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
我唯一的問題(至少到目前爲止)與此查詢是我需要檢索我的第二個表中最後一行的average_cost_price
。
您可以在SQLFiddle中試試以下查詢,並參閱下圖瞭解我所指的內容。
如果你要檢索的「最後」平均成本價,你需要一個(潛在複雜)子查詢檢索它...並定義您通過「最後」是什麼意思 – Uueerdo
Eching Uueerdo的問題:* \'mov \'中的哪一行是給定值\ item_reference \的最後一行...... \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \「move_date \如果有多行具有相同的最新\'movement_date \',該怎麼辦? \ item \'。\'id \'的不同值?哪一行是「最後一行」? – spencer7593
@ spencer7593,我的SQLFiddle在ID中是錯誤的..顯然它是自動遞增的,所以它的(1,2,3)而不是(1,1,1)。我想檢索最後一個ID,在這種情況下,它將是值爲37.30的第3行。請參閱新的SQLFiddle http://sqlfiddle.com/#!9/54ef0/1 – Linesofcode