我有一个库存表,其中有记录,这些记录是指公司出售的产品的库存移动。根据库存移动的类型,移动具有“输入”,“输出”参数。它还有另一列说明“收货”或“外发”的类型...例如由于新库存的到来而进货,由于客户的购买而离去...等...
现在我正在做一个报告,我要列出很长一段时间未售出的产品。因此,请进行以下查询...
SELECT p.id as pid, product_name, DATEDIFF(NOW(), MAX(case when movement_type='OUTGOING' and movement_type_category='PURCHASED' then movement_on end)) AS unsold_days_since_last_sale, DATEDIFF(NOW(), MIN(case when movement_type='INCOMING' and movement_type_category='NEW_STOCK' and quantity>0 then movement_on end)) AS unsold_days_since_first_inventory_in, MAX(case when movement_type='INCOMING' and movement_type_category='NEW_STOCK' and quantity>0 then movement_on end) AS last_inv_in from inventory_movement im left join products p on im.product = p.id GROUP BY product having last_inv_in > 0 ORDER BY unsold_days_since_last_sale desc limit 100
并且我得到如图所示的以下输出。 此输出几乎是正确的,但存在一个问题。如果某个产品过去甚至从未售出过一次,那么我试图获取CURRENT DAY和LAST SOLD DAY之间不同的天数的列将返回null。在那种情况下,我需要该产品的CURRENT DAY和FIRST INVENTORY IN的DAYS差值在适当的位置,以便我可以使该列降序排列并获得输出。但是我只能将这些数据作为2个不同的列而不是作为一列来获取。有人可以帮助我编写查询以将其作为组合列获取,以便我可以对该数据进行排序以获得结果。还要附上我的库存移动表快照,以显示数据的样子...
答案 0 :(得分:0)
我认为IfNull函数可以解决您的问题。
这里是修改后的查询。
SELECT p.id AS pid,
product_name,
Datediff(Now(), Ifnull(Max(CASE
WHEN movement_type = 'OUTGOING'
AND movement_type_category =
'PURCHASED' THEN
movement_on
end), Min(CASE
WHEN movement_type = 'INCOMING'
AND movement_type_category =
'NEW_STOCK'
AND quantity > 0 THEN
movement_on
end))) AS
unsold_days_since_last_sale,
Datediff(Now(), Min(CASE
WHEN movement_type = 'INCOMING'
AND movement_type_category = 'NEW_STOCK'
AND quantity > 0 THEN movement_on
end)) AS
unsold_days_since_first_inventory_in,
Max(CASE
WHEN movement_type = 'INCOMING'
AND movement_type_category = 'NEW_STOCK'
AND quantity > 0 THEN movement_on
end) AS last_inv_in
FROM inventory_movement im
LEFT JOIN products p
ON im.product = p.id
GROUP BY product
HAVING last_inv_in > 0
ORDER BY unsold_days_since_last_sale DESC
LIMIT 100