提供个思路,欢迎其他大佬指正
注意使用 排序(seq),group by,union all
SELECT
f.*
FROM
(
SELECT
cus_id,
max( cusname ) cusname,
NULL dodate,
sum( money ) sumMoney,
NULL payed,
NULL unpayed,
1 seq
FROM
tb_outbase
GROUP BY
cus_id UNION ALL
SELECT
cus_id,
cusname cusname,
dodate dodate,
NULL sumMoney,
pay_money payed,
NULL unpayed,
2 seq
FROM
tb_paycollect UNION ALL
SELECT
cus_id,
'小计' cusname,
NULL dodate,
sum( money ) sumMoney,(
SELECT
IFNULL( sum( pay_money ), 0 )
FROM
tb_pay
WHERE
cus_id = tb_outbase.cus_id
) payed,
sum( money )-(
SELECT
IFNULL( sum( pay_money ), 0 )
FROM
tb_pay
WHERE
cus_id = tb_outbase.cus_id
) unpayed,
3 seq
FROM
tb_outbase
GROUP BY
cus_id
) f
ORDER BY
f.cus_id,
f.seq,
f.dodate