我有一个查询是在单个表上使用多个语句。我可以在哪里更改以优化查询?
查询是从具有多项选择的单个表中获取计数,我需要减小查询大小并优化查询。
select DISTINCT
UM.Name as SalesExeceutiveName,
MTPDet.FromDate,
MTPDet.ToDate,
(select Name from UserMaster where id=MTP.CreatedBy) as CreatedBy,
(select Top 1 RM.Name
from MTPDetailsStatusHistory MDSH
inner join RouteMaster RM ON MDSH.RouteId=RM.Id
where IsActiveRoute=1
and MTPDetailsId=MTPDet.Id
order by MDSH.Id Desc) As RouteName,
ISnull((select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and VisiteTypeId=1 Group By MTPDetailsId,VisiteTypeId),0) As AssignedVisit,
ISnull( (select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and VisiteTypeId=2 Group By MTPDetailsId,VisiteTypeId),0) As UnassignedVisit,
ISnull( (select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and VisiteTypeId=4 Group By MTPDetailsId,VisiteTypeId),0) As FollowUpVisit,
ISnull((select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id),0) As TotalVisit,
ISnull((select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and VisiteTypeId!=6 ),0) As ActualVisit,
ISnull((select Count(VisiteTypeId) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and VisiteTypeId=6 ),0) As CancelledVisit,
ISnull((select Count(IsCheckInOnTime) from MTPVisitMaster where MTPDetailsId=MTPDet.Id and IsCheckInOnTime=0 ),0) As LateEntry,
IsNULL(MtpVM.Distance,0) As Distance,
IsNULL((select Count(Id) from DivisionOrders where OrderDate between MTPDet.FromDate and MTPDet.ToDate and SalesRepresentativeId=MTP.UserId) +
(select Count(Id) from DistributorOrders where OrderDate between MTPDet.FromDate and MTPDet.ToDate and SalesRepresentativeId=MTP.UserId),0) ProductiveVisit,
MtpVM.Remark
from MTPMaster MTP
Inner join MTPDetails MTPDet ON MTP.Id=MTPDet.MTPId
inner join UserMaster UM on UM.Id=MTP.UserId
Inner Join MTPDetailsStatusHistory MtpDetStHistory ON MTPDet.Id=MtpDetStHistory.MTPDetailsId
Inner Join MTPVisitMaster MtpVM ON MtpVM.MTPDetailsId=MTPDet.Id
Inner join VisitType VT ON MtpVM.VisiteTypeId=VT.Id
WHERE MTP.UserId in (SELECT UM.Id As UserId
FROM UserMaster UM
WHERE UM.IsDeleted=0 And UM.Id in (select UserH.UserId
from UserHQ UserH
where UserH.HQId in (select HQM.Id from HQMaster HQM Where HQM.DivisionId=19)) )
我需要使用与前一个相同的输出来优化查询,并进行新的修改。