SELECT 'V' as Ind, A.Voucher_ID, A.Voucher_Prefix, A.Voucher_Type, Ledger, A.Voucher_Date as 'Date', A.Voucher_ID as 'Voucher NO', A.Voucher_Type as 'Voucher Type', DrAmount as 'Dr Amount', CrAmount as 'Cr Amount',  case when running_bal<0 then concat(-1 *running_bal, ' Cr') else concat(running_bal, ' Dr') end as 'Running Balance' FROM ( with subq as (SELECT Against_Ledger, sum(Credit_Amount) as cred,sum(Debit_Amount) as deb,  Voucher_Date, Voucher_ID, Voucher_Type, Voucher_Prefix  From $trans_db.Transaction_Helper Where Ledger_ID='$f1'  GROUP BY Voucher_ID, Voucher_Type, voucher_prefix  ORDER BY Voucher_Date, cast(voucher_id as int), Voucher_Type, _id ) SELECT (SELECT ledger_name FROM $master_db.Ledger_Master where ledger_id = subq.Against_Ledger) AS LEDGER,  subq.Voucher_Date , subq.Voucher_ID , subq.Voucher_Type ,  case when subq.deb  > 0 then subq.deb else 0 end as 'DrAmount',  case when subq.cred  > 0 then subq.cred else 0 end as 'CrAmount',  subq.Voucher_Prefix , sum(subq.deb - subq.cred)  OVER (ORDER BY voucher_date, cast(voucher_id as int), voucher_type) as running_bal  from subq  group by subq.voucher_type, subq.voucher_id, subq.voucher_prefix ) A  WHERE Voucher_Date >=str_to_date('$fromDateTime','%Y-%m-%d') AND Voucher_Date <=str_to_date('$toDateTime','%Y-%m-%d') order by Voucher_Date, cast(voucher_id as int), voucher_type
