2017-09-12 63 views
0

下面的MySQL查詢打開多行的MySQL行成多列和單行

SELECT 
    `FBM_Orders`.`order-id`, 
    `FBM_Orders`.`purchase-date`, 
    `FBM_Orders`.`buyer-name`, 
    `FBM_Orders`.`sku`, 
    `IM_INV`.`LOC_ID`, 
    `IM_INV`.`QTY_ON_HND` 
FROM 
    `FBM_Orders` 
LEFT JOIN `IM_INV` ON `FBM_Orders`.`sku` = `IM_INV`.`ITEM_NO` 
WHERE 
    `FBM_Orders`.`quantity-to-ship` > 0 
ORDER BY 
    `FBM_Orders`.`purchase-date`, 
    `IM_INV`.`LOC_ID` ASC; 

產生

| order-id   | purchase-date   | buyer-name | sku |LOC_ID|QTY_ON_HND| 
|112-9548231-5585051|2017-09-11T21:34:27+00:00|Zacchary Motz|IE51198|AF | 2  | 
|112-9548231-5585051|2017-09-11T21:34:27+00:00|Zacchary Motz|IE51198|LO | 1  | 
|112-9548231-5585051|2017-09-11T21:34:27+00:00|Zacchary Motz|IE51198|S  | 1  | 
|112-9548231-5585051|2017-09-11T21:34:27+00:00|Zacchary Motz|IE51198|SL | 0  | 

我已經有類似的問題的帖子看了看周圍,但他們都使用GROUP_CONCAT,並得到不同的結果比我正在尋找。我想知道如何得到的結果是

| order-id | purchase-date | buyer-name | sku | AF_QTY | LO_QTY | S_QTY | SL_QTY | 
|112-95482..|2017-09-11T21...|Zacchary Motz|IE51198| 2 | 1 | 1 | 0 | 

謝謝

+0

AF,LO的QTY_ON_HND條件和您想要的結果, S&SL是這些固定值,或者可以有更多 –

+0

有時這是4或者沒有。 – enano2054

回答

0

對於設置,你可以使用基於LOC_ID

SELECT 
    o.`order-id`, 
    o.`purchase-date`, 
    o.`buyer-name`, 
    o.`sku`, 
    SUM(CASE WHEN i.`LOC_ID` = 'AF' THEN i.QTY_ON_HND ELSE 0 END) AF_QTY, 
    SUM(CASE WHEN i.`LOC_ID` = 'LO' THEN i.QTY_ON_HND ELSE 0 END) LO_QTY, 
    SUM(CASE WHEN i.`LOC_ID` = 'S' THEN i.QTY_ON_HND ELSE 0 END) S_QTY, 
    SUM(CASE WHEN i.`LOC_ID` = 'SL' THEN i.QTY_ON_HND ELSE 0 END) SL_QTY, 
    i.`LOC_ID`, 
    i.`QTY_ON_HND` 
FROM 
    `FBM_Orders` o 
LEFT JOIN `IM_INV` i ON o.`sku` = i.`ITEM_NO` 
WHERE 
    o.`quantity-to-ship` > 0 
GROUP BY o.`order-id`, 
    o.`purchase-date`, 
    o.`buyer-name`, 
    o.`sku` 
ORDER BY 
    o.`purchase-date` 
+0

可能是一個愚蠢的問題,但只是檢查這應該工作時,有多個訂單的ID是正確的? – enano2054

+0

感謝您的回覆。 – enano2054

+0

是的,它應該工作,因爲組通過包含訂單ID列 –