The code below executes perfectly but I would like to know how to optimize it
select distinct
c.customerid,
Ca.CUAccountID,
c.number,
ca.AccountNumber,
c.name,
b.name as Branch,
cp.description as product,
max(ct.valuedate) as last_deposit_withdrwal_Date,
(ca.CRAmount-ca.DRAmount) as balance,
ca.balancedate,
(case
when max(ct.valuedate) < DATEADD(MM, DATEDIFF(MM, 0, DATEADD(MM, -6, GetDate())), 0)
then 'Dormant'
when max(ct.valuedate) <= DATEADD(MM, DATEDIFF(MM, 0, DATEADD(MM, -3, GetDate())), 0)
then 'Inactive'
else 'Active'
end) as Customer_Status
from
CUAccount CA
join
CUProduct CP on CA.ProductID = Cp.ProductID
join
cutransaction ct on ca.cuaccountid = ct.cuaccountid
join
branches b on ca.BranchID = b.BranchID
join
customer c on ca.customerid = c.customerid
where
CA.Active = 1
and CP.Active = 1
and c.closed = 0
and ct.TransactionTypeID in (1, 2, 256)
and ct.transactionsourceid in (1, 2)
and cp.productid in (117, 118, 119, 120, 121, 122, 123, 124, 125, 158, 168, 58)
group by
c.customerid, c.number, ca.AccountNumber, Ca.CUAccountID,
b.name, c.name, cp.description, (ca.CRAmount-ca.DRAmount), ca.balancedate
having
max(ct.valuedate) > DATEADD(MM, Datediff(MM, 0, dateadd(MM, -3, getdate())), 0)
order by
max(ct.valuedate) asc