Hi All,I have a query I need to re-write as it is taking forever (20+ seconds) to run.The original query is as follows:Select cli_id,cli_companyName,cli_password, count(distinct hov_id)'hovCnt',count(distinct det_id)'DetCnt', sum(tra_AmtDebit)'TotalDebit', sum(tra_AmtCredit)'TotalCredit', 'wITHdRAWN' = (Select sum(tra_AmtDebit) From trans with(NOLOCK) inner join Debtors on tra_det_id = det_id where trs_ven_id =5 and tra_cli_ID = clients.CLI_ID AND (det_status=10) and (tra_transtype='HAndover' or tra_AmtDebit = 0) ) From trans with(NOLOCK) inner join ClientHandOver with(NOLOCK) on tra_hov_id =hov_id inner join Debtors with(NOLOCK) on tra_det_id = det_id inner join Clients with(NOLOCK) on tra_cli_id = cli_id where cli_isAdminOrder = 0 and cli_CompanyStatus <> 5 and trs_ven_id =5 and (tra_transtype='HAndover' or tra_AmtDebit = 0) And det_sta_id =57 group by cli_companyName,cli_id, cli_password order by cli_companyname
After checking the execution plan I found the time is coming from the trans table.Due to its size and constant updating the indexes tend to get fragmented very quickly.Is there a way to not have the nested aggregation 'wITHdRAWN'Bearing in mind the det_status=10 within that nest would need to only apply to the 'wITHdRAWN' and not the other fields in the top level select.Thanks