select r.kunnr,r.waers,
	r.budatd,
	TO_CHAR(to_date(r.budatd,'yyyy-MM') + INTERVAL '-1 MONTH','YYYY-MM') budatb,
	max(r.byxse) as byxse,max(r.byhk) as byhk
from (
	select r1.kunnr,r1.byhk, '0' as BYXSE,r1.budatd,r1.waers from (
		select 
			a.KUNNR,
			round((a.WRBTR_S + a.WRBTR_H),2) as BYHK, 
			a.budatd,a.waers
		from (
			select KUNNR,waers,
			sum(case when shkzg='S' then WRBTR/-1 else 0 end) as WRBTR_S,
			sum(case when shkzg='H' then WRBTR else 0 end) as WRBTR_H,
			budatd
			from bsid2bsad 
			where UMSKZ = '' and BLART in ('DZ', 'ZD')
			GROUP BY KUNNR,budatd,waers
		) a
		where a.budatd is not null
	) r1 
	union all
	select r2.kunnr, '0' as byhk,r2.BYXSE,r2.budatd,r2.waers from (
		select 
			a.KUNNR,
			round((a.WRBTR_S + a.WRBTR_H),2) as BYXSE,
			a.budatd,a.waers
		from (
			select KUNNR,waers,
			sum(case when shkzg='S' then WRBTR else 0 end) as WRBTR_S,
			sum(case when shkzg='H' then WRBTR/-1 else 0 end) as WRBTR_H,
			budatd
			from bsid2bsad 
			where UMSKZ = '' and BLART in ('RV', 'QC')
			GROUP BY KUNNR,budatd,waers
		) a
		where a.budatd is not null
	) r2
) r 
group by r.kunnr,r.budatd,r.waers
order by r.budatd;







/*暂停开发
select 
COALESCE(r2.kunnr,r1.kunnr) as kunnr,
COALESCE(r2.waers,r1.waers) as waers,
COALESCE(r2.budatd,r1.budatc) as budatd,
TO_CHAR(to_date(COALESCE(r2.budatd,r1.budatc),'yyyy-MM') + INTERVAL '-1 MONTH','YYYY-MM') budatb,
COALESCE(r2.byxse,0) as byxse,
COALESCE(r1.budatc,r2.budatd) as budatc,
COALESCE(r1.byhk,0) as byhk
from (
	select 
		a.KUNNR,
		round((a.WRBTR_S + a.WRBTR_H),2) as BYXSE,
		a.budatd,a.waers
	from (
		select KUNNR,waers,
		sum(case when shkzg='S' then WRBTR else 0 end) as WRBTR_S,
		sum(case when shkzg='H' then WRBTR/-1 else 0 end) as WRBTR_H,
		budatd
		from bsid2bsad 
		where UMSKZ = '' and BLART in ('RV', 'QC')
		GROUP BY KUNNR,budatd,waers
	) a
	where a.budatd is not null and a.kunnr = '0001000167' order by a.budatd
) r2 full join (
	select 
		a.KUNNR,
		round((a.WRBTR_S + a.WRBTR_H),2) as BYHK, 
		a.budatc,a.waers
	from (
		select KUNNR,waers,
		sum(case when shkzg='S' then WRBTR/-1 else 0 end) as WRBTR_S,
		sum(case when shkzg='H' then WRBTR else 0 end) as WRBTR_H,
		budatc
		from bsid2bsad 
		where UMSKZ = '' and BLART in ('DZ', 'ZD')
		GROUP BY KUNNR,budatc,waers
	) a
	where a.budatc is not null and a.kunnr = '0001000167' order by a.budatc
) r1 on r2.kunnr = r1.kunnr and r2.budatd = r1.budatc
order by COALESCE(r2.budatd,r1.budatc),COALESCE(r1.budatc,r2.budatd)
*/