SELECT d.idvouchertype,t.name AS voucher_type,d.flag,d.prepayFlag, COUNT(*) AS row_count,SUM(d.amount) AS amount,SUM(d.settleAmount) AS settled_amount, MIN(d.voucherDate) AS first_date,MAX(d.voucherDate) AS last_date FROM dbo.ARAP_Detail d LEFT JOIN dbo.SM_VoucherType t ON t.id=d.idvouchertype WHERE d.idpartner=:customer_id AND d.voucherDate<:cutoff AND d.isArFlag=1 GROUP BY d.idvouchertype,t.name,d.flag,d.prepayFlag;