2015-06-25 19 views
0

我試圖做一個表中的多個選擇,但它只顯示最後一個選擇語句。在存儲過程中的多重選擇

CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10)) 
BEGIN 
    (select tran_date as tran_date 
     from TM_matbalance 
     where Mate_code=Matecode); 

    (select Mate_code as Mate_code 
     from TM_matbalance 
     where Mate_code=Matecode);  

    (select tran_qtyx as Qty_in 
     from TM_matbalance 
     where tran_type='IN' 
     and mate_code=matecode); 

    (select tran_qtyx as Qty_out 
     from TM_matbalance 
     where tran_type='OUT' 
     and mate_code=matecode);  
    END 

我試圖在每個select語句後將分號更改爲逗號,但它表示語法錯誤:缺少'分號'。 請幫忙。

+0

您能否提供一些數據和期望的輸出? –

+0

這裏有一些數據和所需的輸出: [鏈接](http://tinypic.com/r/2zxs8qe/8) – Syns

回答

0

我看你的問題,我想我解決它。

基本上這裏存在兩個問題第一個是要透視表,其中的Tran_Qtyx列Tran_Type列(IN或OUT)成爲Qty_In和Qty_Out價值基於...的問題那部分,你這個查詢解決

SELECT Tran_Date, Mate_Code, 
     SUM(CASE WHEN Tran_Type = 'IN' THEN Tran_Qtyx ELSE 0 END) Qty_In, 
     SUM(CASE WHEN Tran_Type = 'OUT' THEN Tran_Qtyx ELSE 0 END) Qty_Out 
FROM myTable 
WHERE Mate_Code = 'MAT001' 
GROUP BY DATE(Tran_Date) 

注意:在您期望的結果中,我只看到'MAT001'作爲Mate_Code,因此我堅持使用該解決方案,並從結果中排除MAT002。

有關數據透視表的更多信息,您可以閱讀here,那裏可以找到一個鏈接,該鏈接很適合查看,以及可以在哪裏找到許多關於mysql查詢的內容。

問題的第二部分是獲取Qty_Balance列。類似的問題解決了here。這是如何根據前一行中的值計算行值的。

所以,你的完整的查詢看起來是這樣的:

SELECT t1.Tran_Date, t1.Mate_Code, t1.Qty_In, t1.Qty_Out, 
     @b := @b + t1.Qty_In - t1.Qty_Out AS Qty_Balance 
FROM 
(SELECT @b := 0) AS dummy 
CROSS JOIN 
(SELECT Tran_Date, Mate_Code, 
     SUM(CASE WHEN Tran_Type = 'IN' THEN Tran_Qtyx ELSE 0 END) Qty_In, 
     SUM(CASE WHEN Tran_Type = 'OUT' THEN Tran_Qtyx ELSE 0 END) Qty_Out 
FROM myTable 
WHERE Mate_Code = 'MAT001' 
GROUP BY DATE(Tran_Date)) AS t1 
ORDER BY t1.Tran_Date; 

注意:可能只認爲你應該在這裏改變的是表名,這是應該工作。

這是SQL Fiddle所以你可以看到這是如何工作!

GL!

+0

yeaa它的工作原理,我從來沒有想過使用樞軸之前猜我需要學習更難。 謝謝先生。 – Syns

+0

@Syns不客氣。我很高興我可以幫助:) –

0

您需要將您的查詢結構爲一體,或傳遞參數給存儲過程來選擇哪個輸出/查詢你想要的,調整你的查詢,你會需要這樣的東西:

`CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10)) 
BEGIN 
(select tran_date as tran_date, Mate_code as Mate_code, tran_qtyx as Qty 
    from TM_matbalance 
    where Mate_code=Matecode 
    and (tran_type='IN' or tran_type='OUT'); 
END` 

或者試試這個,如果你有一個ID列:

SELECT coalesce(ta.id, tb.id) as tran_id, coalesce(ta.tran_date, tb.tran_date) as tran_date, coalesce(ta.Mate_code, tb.Mate_code) as Mate_code, ta.tran_type as Qty_In, tb.tran_type as Qty_Out 
from (select ta.* 
    from TM_matbalance ta 
    where ta.tran_type = 'IN' 
and Mate_code=Matecode 
) ta full outer join 
(select tb.* 
    from TM_matbalance tb 
    where tb.tran_type = 'OUT' 
and Mate_code=Matecode 
) tb 
on ta.id = tb.id ; 

只需更換「ID」與您的ID列的名稱,如果你不需要返回id列然後刪除coalesce(ta.id, tb.id) as tran_id

+0

哇謝謝你,聲明是工作,但如何將tran_qtyx分開qty_in和qty_out?所以結果將是「tran_date,mate_code,qty_in,qty_out」 我試着添加另一個'select'語句,但它不起作用。 – Syns

+0

在你的編碼環境中,你有沒有辦法處理這個問題? – Dave

+0

Like if(Qty ==「IN」){Do something} else if(Qty ==「OUT」){Do something else} else {Do this} – Dave