You should create a view that gives you the date you want then when you create all those amount columns you can just use the date without that extra CASE for every column. Here is how the view could be, I named the date ActiveDate. I also joined the payee table instead of using an IN in the WHERE clauseCREATE VIEW MyViewASSELECT a.company_id, a.payee_id, a.amount, a.ready_to_pay_flag, a.deduction_type, CASE WHEN b.order_id IS NULL THEN a.transaction_date ELSE b.delivery_date END AS ActiveDateFROM drs_pending_deduct as a INNER JOIN payee p ON a.payee_id = p.[id]LEFT OUTER JOIN settlement as b ON a.order_id = b.order_id WHERE a.company_id = 'TMS2' AND p.status = 'A' AND p.non_office_emp = 'Y' AND p.company_id = 'TMS2' AND a.ready_to_pay_flag <> 'V' AND a.amount is not null
Your query now becomes something likeSELECT company_id, payee_id,sum( CASE WHEN ready_to_pay_flag = 'Y' AND deduction_type = 'E' THEN amount END) earn_amount_rtp, sum( CASE WHEN ready_to_pay_flag = 'Y' AND deduction_type = 'E' AND datediff(d,( ActiveDate, '2007-03-12 23:59:59') <= 30 THEN amount END) earn_amount_rtp_current,...FROM MyViewGROUP BY company_id, payee_id