2016-01-20 43 views
1

我想製作一個報告系統,我需要爲每個日期顯示報告 。顯示關於特定日期的數據?

enter image description here

這些是selected_items enter image description here 我的表架構這是stock_list enter image description here

我在前端,後端和java使用PHP來顯示 數據。我嘗試了幾個查詢來獲得所需的輸出,但是我遠遠得不到它。這些是我使用的一些查詢。

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); 

這給了我第一個五列,但輸出給了我錯誤的價值觀。 然後我也試過聯盟。

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

謝謝@LordAnomander你能幫助解決方案嗎 – AndroidNewBee

+0

你會共享表格模式嗎? – AnkiiG

+0

是啊@AnkiiG請檢查更新的問題。謝謝 – AndroidNewBee

回答

0

不幸的是,SQL小提琴應聲而我試圖執行這個查詢

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%確定它的工作原理,但它應該是正確的方法。