select t1.sa_writeoffbillid,
       t1.createuserid,
       t1.createby,
       t1.createdate,
       t1.checkby,
       t1.checkdate,
       t1.billnodate,
       t1.status,
       t1.sys_enterpriseid,
       t2.enterprisename,
       t2.abbreviation,
       t1.billno writeoffbillidbillno,
       t1.remarks,
       t1.unwriteoffamount,
       t1.writeoffamount,
       t1.sa_cashbillid,
       t4.billno cashbillidbillno,
       t5.agentnum
from sa_writeoffbill t1
         left join sys_enterprise t2
                   on t1.siteid = t2.siteid and t1.sys_enterpriseid = t2.sys_enterpriseid
         left join sa_agents t5 on t2.siteid = t5.siteid and t2.sys_enterpriseid = t5.sys_enterpriseid
         left join sa_accountclass t3 on t1.siteid = t3.siteid and t1.sa_accountclassid = t3.sa_accountclassid
         left join sa_cashbill t4 on t1.siteid = t4.siteid and t1.sa_cashbillid = t4.sa_cashbillid
where t1.siteid = $siteid$
  and t1.sa_writeoffbillid in
      (SELECT sa_writeoffbillid from sa_writeoffbill_order WHERE sa_orderid = $sa_orderid$ and siteid = $siteid$)
  and $where$
