我有以下查询UNION
两个表并检索某些字段的SUM
和其他信息,如您所见:
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 中尝试以下查询,并查看下面的图片,了解我所指的内容。
答案 0 :(得分:0)
您是否尝试过使用日期“收紧”Where声明?它可能是第一次出现。我建议测试
WHERE mov.movement_date <= '2016-03-31' AND
mov.movement_date >= '2016-03-01'
as
WHERE mov.movement_date <= '2016-03-31' AND
mov.movement_date >= '2016-03-27'
然后,如果它不起作用,您可以将其标记为关闭。 Lemme知道生病试着帮助你。
答案 1 :(得分:0)
<强>解决强>
我必须使用group_concat
函数来提供订购字段的功能。
group_concat(mov.average_cost_price ORDER BY mov.id DESC SEPARATOR ",")
但是这个函数返回所有值,因为我不能使用LIMIT
函数,所以我使用substring_index
函数只返回一个值。
substring_index(group_concat(mov.average_cost_price ORDER BY mov.id DESC SEPARATOR ","), ",", 1) as `average_cost_price`