我收到的结果:
id sku name GROUP_CONCAT(quantity_received) GROUP_CONCAT(item_cost)
4 00004 Antibacterial Wipes 50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309,50,14,25,309 3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49,3.29,3.29,3.29,3.49
我想要的结果:
id sku name GROUP_CONCAT(DISTINCT quantity_received) GROUP_CONCAT(DISTINCT item_cost)
4 00004 Antibacterial Wipes 50,14,25,309 3.29,3.49
我解决此问题的方法是将DISTINCT放入quantity_recieved选择中。问题是,如果数量有两个相同的值,如50,50,14,25。结果将是50,14,25。我只是想摆脱重复的数字,只得到一次值。
以下是查询:
SELECT `product`.`id`,`product`.`sku`,`product`.`name`,
case when coalesce(stock1.`quantity`, '') = ''
then '0'
else stock1.`quantity`
end as qty_warehouse,
case when coalesce(sum(distinct stock2.`quantity`), '') = ''
then '0'
else sum(distinct stock2.`quantity`)
end as qty_events,
case when coalesce(stock1.`quantity`, '') = ''
then '0'
else stock1.`quantity`
end +
case when coalesce(sum(distinct stock2.`quantity`), '') = ''
then '0'
else sum(distinct stock2.`quantity`)
end as qty_total
GROUP_CONCAT(DISTINCT quantity_received) ,
GROUP_CONCAT(DISTINCT item_cost)
FROM (`product`)
LEFT JOIN`shipping_event`
ON `shipping_event`.`product_id` = `product`.`id`
LEFT JOIN `product_stock` as stock1
ON `product`.`id` = `stock1`.`product_id` and `stock1`.`location_id` = 112
LEFT JOIN `product_stock` as stock2
ON `product`.`id` = `stock2`.`product_id` and `stock2`.`location_id` != 112
LEFT JOIN `shipping_list`
ON `shipping_event`.`shipping_list_id` = `shipping_list`.`id`
WHERE `shipping_list`.`type` = 'incoming'
AND `shipping_event`.`end_date` > '2004-01-01 01:01:01'
GROUP BY `product`.`id`
ORDER BY `sku` asc LIMIT 20
我正在使用group concat来显示这种情况下的结果。我实际上将quantity_received相加,然后按项目成本加倍。
答案 0 :(得分:1)
您可以使用GROUP BY
然后JOIN
创建一个子查询到product
表。
同样的逻辑也可以应用于其他连接表。如果您这样做,可以跳过GROUP BY product.id
:
SELECT p.id
, p.sku
, p.name
, COALESCE(stock1.quantity, 0) --- minor improvements on
AS qty_warehouse --- the long CASE clauses
, COALESCE(SUM(DISTINCT stock2.quantity), 0)
AS qty_events
, COALESCE(stock1.quantity, 0) + COALESCE(SUM(DISTINCT stock2.quantity), 0)
AS qty_total
, grp.all_quantities_received
, grp.all_item_costs
FROM product AS p
LEFT JOIN
( SELECT product_id
, GROUP_CONCAT(se.quantity_received) AS all_quantities_received
, GROUP_CONCAT(se.item_cost) AS all_item_costs
FROM shipping_event AS se
LEFT JOIN shipping_list AS sl
ON se.shipping_list_id = sl.id
WHERE sl.type = 'incoming'
AND se.end_date > '2004-01-01 01:01:01'
GROUP BY se.product_id
) AS grp
ON grp.product_id = p.id
LEFT JOIN `product_stock` AS stock1
ON p.id = stock1.product_id
AND stock1.location_id = 112
LEFT JOIN product_stock AS stock2
ON p.id = stock2.product_id
AND stock2.location_id <> 112
GROUP BY p.id
ORDER BY sku ASC
LIMIT 20