无法在mysql中使用UNION在单独的列中显示数据?

时间:2016-01-19 12:17:38

标签: php mysql

  

我编写了一个mysql查询,它从两个不同的数据中获取数据   表格stock_listselected_items使用union.From stock_list   我得到SUM(数量),SUM(重量).From selected_items我得到了   COUNT(条形码)和SUM(重量)均基于特定日期   union中的最后一个查询返回总SUM(qty),SUM(权重)   来自stock_list。这是我正在使用的查询。

SELECT SUM( qty ) AS StockSum, SUM( weight ) AS Stockweight
FROM  `stock_list` 
WHERE DATE LIKE  '08-Jan-2016'
UNION SELECT COUNT( barcode ) AS BilledItems, SUM( weight ) AS Billedweight
FROM  `selected_items` 
WHERE DATE LIKE  '08-Jan-2016'
UNION SELECT SUM( qty ) AS TotalStock, SUM( weight ) AS TotalWeight
FROM  `stock_list`;
  

问题是所有内容都显示在两列StockSum和   Stockweight。我希望有6个单独的列加​​上我想要的   在开头为日期添加额外的列。

     

这是我目前的输出。

enter image description here

  

这是我想要实现的理想结果。enter image description here

这是我的selected_items表。 enter image description here

这是我的stock_list表enter image description here

1 个答案:

答案 0 :(得分:1)

这是我想到的前4列的方法:

SELECT date,
       SUM( qty ) AS StockSum,
       SUM( stockW ) AS Stockweight,
       COUNT( barcode ) AS BilledItems,
       SUM( billedW ) AS Billedweight
FROM ( SELECT
          date,
          qty, weight AS stockW,
          null AS barcode, null AS billedW
       FROM stock_list
       UNION
       SELECT
          date,
          null AS qty, null AS stockW,
          barcode, weight AS billedW
       FROM selected_items
     )
GROUP BY date
ORDER BY date

对于最后两列,我认为您希望在该日期对每个日期运行总计库存,并编程,我使用PHP进程而不是SQL。