I am having some troubles when combining left joins with optional values to group by.
In short we have
and we are trying to get the stock total qty, where
even simpler
I hope it is clear ... the query below is not working. Step 1 to me looked like just getting the parent ID in a column
and step 2 is to sum the qty's for simple products per simple product and for parent products sum it up for all child simple product but show the parent data
select c.sku as sku,
IFNULL(pr.parent_id, c.entity_id) as main_id,
c.type_id as type,
SUM(CASE WHEN (wh.code='LR') THEN FLOOR(wp.qty) ELSE 0 END) AS 'Loc1',
SUM(CASE WHEN (wh.code='LS') THEN FLOOR(wp.qty) ELSE 0 END) AS 'Loc2'
FROM catalog c,
wh_products wp,
warehouses wh
LEFT JOIN catalog_product_relation pr ON pr.parent_id = c.entity_id
WHERE c.entity_id = wp.product_id and wp.warehouse_id = wh.warehouse_id and wp.qty > 0
GROUP BY main_id
I would start by writing the JOIN
s correctly and aggregating by the columns in the SELECT
:
SELECT c.sku as sku,
COALESCE(pr.parent_id, c.entity_id) as main_id, c.type_id as type,
SUM(CASE WHEN wh.code = 'LR' THEN FLOOR(wp.qty) ELSE 0 END) AS Loc1,
SUM(CASE WHEN wh.code = 'LS' THEN FLOOR(wp.qty) ELSE 0 END) AS Loc2
FROM catalog c LEFT JOIN
wh_products wp
ON c.entity_id = wp.product_id LEFT JOIN
warehouses wh
ON wp.warehouse_id = wh.warehouse_id AND wp.qty > 0 LEFT JOIN
catalog_product_relation pr
ON pr.parent_id = c.entity_id
GROUP BY c.sku, COALESCE(pr.parent_id, c.entity_id), c.type_id;
I'm not sure if this fixes your problems. Without sample data and desired results, it is a bit hard to follow the logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.