2015-06-25 20 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