
SELECT
		tb11.bailun_sku bailun_sku,
		tb11.warehouse_code warehouse_code,
		tb11.transfer_order_id transfer_order_id,
		tb5.estimated_arrival_time estimated_arrival_time,
		tb11.create_time create_time,
		( tb11.count - IFNULL( tb4.count, 0 ) ) AS count
FROM
		(
		SELECT
				tb1.bailun_sku,
				tb1.warehouse_code,
				tb1.transfer_order_id,
				tb1.create_time,
				sum( tb1.count ) count
		FROM
				dc_base_transfer_bale tb1
				LEFT JOIN dc_base_transfer_complete tb2 ON tb1.transfer_order_id = tb2.transfer_order_id
		WHERE
				tb2.bailun_sku IS NULL
				AND tb1.bailun_sku = #{bailunSku}
				AND tb1.warehouse_code = #{warehouseCode}
				AND tb1.deleted = 0
		GROUP BY
				bailun_sku,
				warehouse_code,
				transfer_order_id
		) tb11
		LEFT JOIN (
		SELECT
				tb1.bailun_sku,
				tb1.warehouse_code,
				tb1.transfer_order_id,
				tb1.estimated_arrival_time,
				tb1.create_time,
				sum( tb1.count ) count
		FROM
				dc_base_transfer_verify tb1
				LEFT JOIN dc_base_transfer_complete tb2 ON tb1.transfer_order_id = tb2.transfer_order_id
		WHERE
				tb2.bailun_sku IS NULL
				AND tb1.bailun_sku = #{bailunSku}
				AND tb1.warehouse_code = #{warehouseCode}
				AND tb1.deleted = 0
		GROUP BY
				bailun_sku,
				warehouse_code,
				transfer_order_id
		) tb5 ON tb5.bailun_sku = tb11.bailun_sku
		AND tb5.warehouse_code = tb11.warehouse_code
		AND tb5.transfer_order_id = tb11.transfer_order_id
		LEFT JOIN (
		SELECT
				bailun_sku,
				warehouse_code,
				transfer_order_id,
				sum( count ) count
		FROM
				(
				SELECT
						t1.bailun_sku,
						t1.warehouse_code,
						t2.count,
						t1.transfer_order_id
				FROM
						( SELECT max( create_time ) AS create_time, bailun_sku, warehouse_code, transfer_order_id FROM dc_base_transfer_inbound WHERE deleted = 0 AND bailun_sku = #{bailunSku}
						AND warehouse_code = #{warehouseCode} GROUP BY bailun_sku, warehouse_code, transfer_order_id ) t1
						INNER JOIN dc_base_transfer_inbound t2 ON t1.bailun_sku = t2.bailun_sku
						AND t1.warehouse_code = t2.warehouse_code
						AND t1.transfer_order_id = t2.transfer_order_id
						AND t1.create_time = t2.create_time
						LEFT JOIN dc_base_transfer_complete tb2 ON t1.transfer_order_id = tb2.transfer_order_id
				WHERE
						tb2.bailun_sku IS NULL
				) tb3
		GROUP BY
				bailun_sku,
				warehouse_code,
				transfer_order_id
		) tb4 ON tb5.bailun_sku = tb4.bailun_sku
		AND tb5.warehouse_code = tb4.warehouse_code
		AND tb5.transfer_order_id = tb4.transfer_order_id
WHERE
		( tb11.count - IFNULL( tb4.count, 0 ) ) > 0 UNION ALL
SELECT
		bailun_sku,
		warehouse_code,
		transfer_plan_order_id,
		NULL,
		update_time,
		count
FROM
		dc_base_transfer_plan
WHERE
		STATUS = 1
		AND deleted = 0
		AND bailun_sku = #{bailunSku}
		AND warehouse_code = #{warehouseCode}
