MySQL – How to Split and Group Quantities by Child Customer Order

MySQL

I have some data like in picture below on and need to perform some query.

The Datas

And then I try to produce result like the picture below, but I have trouble and don't know how to split qty by child customer order.

How to get results like picture 2?

This is the query I have tried in order to obtain the result I want:

SELECT item
    ,no_po
    ,sum(qty) as total
    ,parent_customer
    ,child_customer
    ,qty 
FROM `detail_order` 
WHERE received_date='2018-06-27' 
group by item 
ORDER BY item asc

The Result What I wanted

Best Answer

select item, no_po, sum(qty) qty_total,
    sum(case when parent_customer='Customer B' and child_customer='ha' then qty else 0 end) as customer_b_ha,
    sum(case when parent_customer='Customer B' and child_customer='he' then qty else 0 end as customer_b_he,
    sum(case when parent_customer='Customer B' and child_customer='hi' then qty else 0 end as customer_b_hi,
    sum(case when parent_customer='Customer B' and child_customer='ho' then qty else 0 end as customer_b_ho,
    sum(case when parent_customer='Customer B' and child_customer='hu' then qty else 0 end as customer_b_hu,
    sum(case when parent_customer='Customer C' and child_customer='ha' then qty else 0 end as customer_c_ha,
    sum(case when parent_customer='Customer C' and child_customer='he' then qty else 0 end as customer_c_he,
    sum(case when parent_customer='Customer C' and child_customer='hi' then qty else 0 end as customer_c_hi,
    sum(case when parent_customer='Customer C' and child_customer='ho' then qty else 0 end as customer_c_ho,
    sum(case when parent_customer='Customer C' and child_customer='hu' then qty else 0 end as customer_c_hu
from detail_order
where received_date='2018-06-27' 
group by item, no_po
order by item asc, no_po