MySQL Union All - 值优先级

时间:2016-04-28 17:27:48

标签: mysql sql

我有以下查询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 中尝试以下查询,并查看下面的图片,了解我所指的内容。

enter image description here

2 个答案:

答案 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`

GROUP_CONCAT with limit