Mysql Pivot表:如何获取行和列总计并添加条件列?

时间:2013-01-12 03:00:07

标签: mysql

我有两个名为tabItem和tabBin的表。现在,数据以Pivot表格式通过下面提到的代码获取。现在,下面的代码按预期工作,但我无法添加列和行总字段。

现在行总数不是基于行中的所有单元格,而是我想要连续排列以下单元格,列标题是1D + 2B + BRG + BHT,我无法找到方法为此,我们需要将此列命名为“Total”。

此外,我还需要添加另一列,以打印以下内容:

  1. 如果1D + 2B<那么“1 CORD”
  2. 如果总计< SO + ROL然后“2 CSTK”
  3. 同样有许多其他条件类似于10~15个条件,我只是不知道如何编写代码,因为提到的所有代码都是通过在谷歌上搜索而写的,但现在我无法找到答案而且我我完全不熟悉mysql。任何帮助都将受到高度赞赏。

    select 
     `tabItem`.name as "Item Code:Link/Item:150",
     `tabItem`.description as "Description::300",
     ifnull(`tabItem`.re_order_level,0) as "ROL:Currency:50",
     ifnull(`tabBin`.reserved_qty,0) as "SO:Currency:50",
     ifnull(`tabBin`.ordered_qty,0) as "PO:Currency:50",
     ifnull(min(case when `tabBin`.warehouse="DEL20A" then `tabBin`.actual_qty end),0) as "1D:Currency:50",  
     ifnull(min(case when `tabBin`.warehouse="BGH655" then `tabBin`.actual_qty end),0) as "2B:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="RG-BGH655" then `tabBin`.actual_qty end),0) as "BRG:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="HT-BGH655" then `tabBin`.actual_qty end),0) as "BHT:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="FG-BGH655" then `tabBin`.actual_qty end),0) as "BFG:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="SLIT-DEL20A" then `tabBin`.actual_qty end),0) as "DSL:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="RG-DEL20A" then `tabBin`.actual_qty end),0) as "DRG:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="FG-DEL20A" then `tabBin`.actual_qty end),0) as "DFG:Currency:50", 
     ifnull(min(case when `tabBin`.warehouse="TEST-DEL20A" then `tabBin`.actual_qty end),0) as "DTS:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="REJ-DEL20A" then `tabBin`.actual_qty end),0) as "DRJ:Currency:50",   
     ifnull(min(case when `tabBin`.warehouse="RM-DEL20A" then `tabBin`.actual_qty end),0) as "DRM:Currency:50",    
     ifnull(min(case when `tabBin`.warehouse="RM-BGH655" then `tabBin`.actual_qty end),0) as "BRM:Currency:50"  
     from
     `tabItem`
     left join `tabBin` on
     `tabItem`.name = `tabBin`.item_code
    where
     `tabBin`.item_code <>""
     and `tabBin`.item_code = `tabItem`.name    
    group by `tabItem`.name
    order by `tabItem`.name asc
    

1 个答案:

答案 0 :(得分:0)

尝试使用子查询执行此操作。使用您的查询。 。

select t.*,
       ("1D:Currency:50" + "2B:Currency:50" + "BRG:Currency:50" + "BHT:Currency:50"
       ) as tot1,
       (case when "1D:Currency:50" + "2B:Currency:50" < "SO:Currency:50"
             then '1 CORD'
             when ("1D:Currency:50" + "2B:Currency:50" + "BRG:Currency:50" + "BHT:Currency:50" < "SO:Currency:50" + "ROL:Currency:50"
             then  "2 CSTK"
         end)
from (<your query>) t

这可以让您了解如何继续。