2017-08-15 168 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

此答案與您的原始問題無關。這個查詢應該做什麼? –