select ACC as ACCID, ACCOUNT.ITSNUMBER, ACCOUNT.ITSNAME, SUBACC, SUBACCID, SUBACCTYPE,
case when ACCOUNT.NORMALBALANCETYPE = 0 then ALL_RECORDS.DEBIT - ALL_RECORDS.CREDIT
else 0 end as DEBIT,
case when ACCOUNT.NORMALBALANCETYPE = 1 then ALL_RECORDS.CREDIT - ALL_RECORDS.DEBIT
else 0 end as CREDIT
from
  (
    select ACC, SUBACC, SUBACCID, sum(DEBIT) as DEBIT, sum(CREDIT) as CREDIT
    from 
      (
        select ITSACCOUNT as ACC, SUBACCOUNT as SUBACC, SUBACCID,
        case when ACCOUNTIN.NORMALBALANCETYPE = 0 then ITSBALANCE
        else 0 end as DEBIT,
        case when ACCOUNTIN.NORMALBALANCETYPE = 1 then ITSBALANCE
        else 0 end as CREDIT
        from  BALANCEAT
        join ACCOUNT as ACCOUNTIN on BALANCEAT.ITSACCOUNT = ACCOUNTIN.ITSID 
        where ITSDATE = :DATE1
        
        union all

        select ACCDEBIT as ACC, SUBACCDEBIT as SUBACC, SUBACCDEBITID as SUBACCID, sum(DEBIT) as DEBIT, 0.00 as CREDIT
        from  ACCOUNTINGENTRY 
        where ITSDATE >= :DATE1 and ITSDATE <= :DATE2
        group by ACC, SUBACC, SUBACCID
        
        union all
        
        select ACCCREDIT as ACC, SUBACCCREDIT as SUBACC, SUBACCCREDITID as SUBACCID, 0 as DEBIT, sum(CREDIT) as CREDIT
        from  ACCOUNTINGENTRY 
        where ITSDATE >= :DATE1 and ITSDATE <= :DATE2
        group by ACC, SUBACC, SUBACCID
      ) as UNION_RECORDS
    group by ACC, SUBACC, SUBACCID
  ) as ALL_RECORDS
join ACCOUNT on ALL_RECORDS.ACC = ACCOUNT.ITSID
order by ACCOUNT.ITSNUMBER, SUBACC;
