-- 更新开单记录表中的储扣金额，使其等于储扣详情表中汇总的金额
-- 只更新那些储扣金额不一致的记录（包括NULL、0或金额不匹配的情况）

UPDATE lq_kd_kdjlb kd
INNER JOIN (
    SELECT 
        F_BillingId,
        COALESCE(SUM(F_Amount), 0) as total_amount
    FROM lq_kd_deductinfo
    WHERE F_IsEffective = 1
    GROUP BY F_BillingId
) deduct_sum ON kd.F_Id = deduct_sum.F_BillingId
SET kd.F_DeductAmount = deduct_sum.total_amount
WHERE kd.F_IsEffective = 1
    AND (
        kd.F_DeductAmount IS NULL 
        OR kd.F_DeductAmount = 0 
        OR ABS(kd.F_DeductAmount - deduct_sum.total_amount) > 0.01
    )
    AND deduct_sum.total_amount > 0;

