-- 此SQL用于查询商品库存与格口库存不一致的数据
-- 筛选条件：商品库存 < 格口库存（说明格口库存超出商品库存，需要重新计算）
-- 主要用途：发现库存异常数据，定位需要重新计算格口数据的商品
SELECT 
    sg.goods_id,
    sg.goods_name,
    sg.stock AS '商品库存',
    COALESCE(SUM(cc.stock), 0) AS '格口库存',
    sc.cabinet_name,
    GROUP_CONCAT(DISTINCT cc.cell_no ORDER BY cc.cell_no ASC) AS '格口号'
FROM 
    shop_goods sg
LEFT JOIN 
    cabinet_cell cc ON sg.goods_id = cc.goods_id 
    AND cc.deleted = 0
    AND cc.goods_id IS NOT NULL
LEFT JOIN
    smart_cabinet sc ON cc.cabinet_id = sc.cabinet_id
    AND sc.deleted = 0
WHERE 
    sg.deleted = 0
GROUP BY 
    sg.goods_id,
    sg.goods_name,
    sg.stock,
    sc.cabinet_id,
    sc.cabinet_name
HAVING 
    sg.stock < COALESCE(SUM(cc.stock), 0)
    AND sc.cabinet_name IS NOT NULL
ORDER BY 
    sg.goods_id,
    sc.cabinet_name;