with un as (SELECT *, SUM(val) over (partition by name order by ttype) vsum
FROM t1112a
UNION ALL
SELECT *,
SUM(val) over (partition by name order by ttype) vsum
FROM t1112b),
rnk as (
SELECT *, ROW_NUMBER() over (partition by name order by vsum)
FROM un),
cte as (
SELECT name,ttype,vsum,
if(left(ttype, 2) = '收款', lead(ttype) over (partition by name), ttype) val1,
vsum - lag(vsum, 1, 0) over (partition by name) val,
if(left(ttype, 2) = '发票', lead(ttype) over (partition by name), ttype) val2
from rnk)
SELECT name, val1, val,val2,vsum, if(left(val2, 2) = '发票', lead(val2) over (partition by name), val2) val2
FROM cte
where val1 is not null
and val2 is not null