2017-08-15 68 views
0

UNION我有这个疑问:集团通过与MariaDB的

select item_code, item_name, First, Second, Third, `Fourth` from (
      (SELECT t.item_code, i.item_name, t.actual_qty AS `First`, '' AS `Second`, '' AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Finished Goods") 
      UNION 
      (SELECT t.item_code, i.item_name, '' AS `First`, t.actual_qty AS `Second`, '' AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 01 - 1200 KG") 
      UNION 
      (SELECT t.item_code, i.item_name, '' AS `First`, '' AS `Second`, t.actual_qty AS `Third`, '' AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 02 - 1200 KG") 
      UNION 
      (SELECT t.item_code, i.item_name, '' AS `First`, '' AS `Second`, '' AS `Third`, t.actual_qty AS `Fourth` FROM tabBin t JOIN `tabItem` i ON i.name = t.item_code WHERE t.warehouse = "Tank 03 - 1200 KG")) as temp 
      GROUP BY temp.item_code, temp.item_name, temp.First, temp.Second, temp.Third, temp.Fourth 

这是输出:

item_code item_name first, second, third, fourth 
fg-plu  PLUM       30.000000 
fg-plu  PLUM     40.000000 
fg-plu  PLUM   10.000000  
fg-plu  PLUM 1248.00 

我想组由item_codeitem_name或只是item_code

+0

那么不要使用UNION,而是一个普通的子查询......? – CBroe

+0

会返回很多行。我不知道这是否会继续工作 –

+0

这被称为“pivoting” - 按照我添加的标签。 –

回答

0

这看起来确实是一个变相查询。只要使用MAXCASE表达式来得到你想要的输出:

SELECT 
    t.item_code, 
    i.item_name, 
    MAX(CASE WHEN t.warehouse='Finished Goods' THEN t.actual_qty END) AS first, 
    MAX(CASE WHEN t.warehouse='Tank 01 - 1200 KG' THEN t.actual_qty END) AS second, 
    MAX(CASE WHEN t.warehouse='Tank 02 - 1200 KG' THEN t.actual_qty END) AS third, 
    MAX(CASE WHEN t.warehouse='Tank 03 - 1200 KG' THEN t.actual_qty END) AS fourth 
FROM tabBin t 
INNER JOIN tabItem i 
    ON i.name = t.item_code 
GROUP BY 
    t.item_code, 
    i.item_name 
+0

感谢您的帮助,但我解决了这个问题 –

0

解决了

enter code Select i.item_name,IFNULL((select b.actual_qty as i2total 
     from `tabItem` as i2 
      join `tabBin` as b on b.item_code = i2.item_code AND i2.item_code = i2.item_code 
     where b.warehouse = "Finished Goods" AND i2.item_code = i.item_code),0) foa, IFNULL((select b.actual_qty as i2total 
     from `tabItem` as i2 
      join `tabBin` as b on b.item_code = i2.item_code AND i2.item_code = i2.item_code 
     where b.warehouse = "Toros" AND i2.item_code = i.item_code),0) toros, (foa + toros) AS total FROM `tabItem` as i WHERE i.item_group = "products" GROUP BY i.item_name, foa, toros ; 

谢谢大家的帮助。

+0

此答案与您的原始问题无关。这个查询应该做什么? –