我正在尝试创建一个需要显示报告的报告系统 每个日期。
这些是selected_items 的表格架构 这是stock_list
我在后端使用php并在前端使用java来显示 数据。我尝试了几个查询来获得所需的输出但是这样 我无法得到它。这些是我用过的一些问题。
SELECT
COALESCE(stock_list.date, selected_items.date) AS date,
SUM( stock_list.qty ) AS StockSum,
SUM( stock_list.weight ) AS Stockweight,
COUNT( selected_items.barcode ) AS BilledItems,
SUM( selected_items.weight ) AS Billedweight
FROM stock_list join selected_items
ON stock_list.date = selected_items.date
GROUP BY COALESCE(stock_list.date, selected_items.date)
ORDER BY COALESCE(stock_list.date, selected_items.date);
这给了我前五列,但输出给了我错误的值。 然后我也尝试了Union。
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`;
这里我得到了四列的正确值,但问题是当我希望它在4列时,>结果显示在两列中。 任何人都可以指导我,我已经想到了它的java部分,但我不擅长php和mysql。 谢谢
答案 0 :(得分:0)
不幸的是,在我尝试执行此查询时,SQL Fiddle崩溃了
SELECT sl.date AS date, B.qtySum AS StockSum, B.weightSum AS Stockweight,
C.barcodeCount AS BilledItems, C.weightSum AS Billedweight
FROM stock_list sl
JOIN (SELECT SUM(qty) as qtySum, SUM(weight) as weightSum
FROM STOCK_LIST GROUP BY date) AS B
ON B.date = sl.date
JOIN (SELECT SUM (weight) AS weightSum, COUNT(barcode) AS barcodeCount
FROM SELECTED_ITEMS GROUP BY date) AS C
ON C.date = sl.date;
As it was tried here。连接的问题是行将连接多次,因此总和会出错。例如,您有四行从第二个表连接,因此总和应该是它的四倍。使用子查询,您可以避免此问题,因为您在加入变量之前对变量进行计数和求和,因此数字应该适合。唉,我无法运行查询,所以我不能100%确定它有效,但它应该是正确的方法。