提供个思路,欢迎其他大佬指正
注意使用 排序(seq),group by,union all
SELECTf.*
FROM(SELECTcus_id,max( cusname ) cusname,NULL dodate,sum( money ) sumMoney,NULL payed,NULL unpayed,1 seq FROMtb_outbase GROUP BYcus_id UNION ALLSELECTcus_id,cusname cusname,dodate dodate,NULL sumMoney,pay_money payed,NULL unpayed,2 seq FROMtb_paycollect UNION ALLSELECTcus_id,'小计' cusname,NULL dodate,sum( money ) sumMoney,(SELECTIFNULL( sum( pay_money ), 0 ) FROMtb_pay WHEREcus_id = tb_outbase.cus_id ) payed,sum( money )-(SELECTIFNULL( sum( pay_money ), 0 ) FROMtb_pay WHEREcus_id = tb_outbase.cus_id ) unpayed,3 seq FROMtb_outbase GROUP BYcus_id ) f
ORDER BYf.cus_id,f.seq,f.dodate