Это чисто догадочный ответ, поскольку у нас нет образцов данных и ожидаемых результатов. Как я уже сказал, похоже, нам здесь нужна условная агрегация. Я удалил много подзапросов, переместил один и превратил их в условные агрегаты.
Хотя здесь много догадок, но это должно быть рядом с тем, что вам нужно,Надеюсь, если это не совсем правильно, вы можете легко исправить это:
SELECT UMse.[Name] as SalesExeceutiveName,
MTPDet.FromDate,
MTPDet.ToDate,
UMc.[Name] AS CreatedBy,
RN.[Name] AS RouteName,
COUNT(CASE WHEN MTPVM.VisiteTypeId = 1 THEN 1 END) AS AssignedVisit,
COUNT(CASE WHEN MTPVM.VisiteTypeId = 2 THEN 1 END) AS UnassignedVisit,
COUNT(CASE WHEN MTPVM.VisiteTypeId = 4 THEN 1 END) AS FollowUpVisit,
COUNT(VisiteTypeId) AS TotalVisit,
COUNT(CASE WHEN MTPVM.VisiteTypeId != 6 THEN 1 END) AS ActualVisit,
COUNT(CASE WHEN MTPVM.VisiteTypeId = 6 THEN 1 END) AS CancelledVisit,
COUNT(CASE WHEN IsCheckInOnTime = 0 THEN 1 END) AS LateEntry,
MTPVM.Distance, --Is is ASSUMED distance is the same for all rows.
--Unlikely this will give a big benefit by being moved
(SELECT Count(DivO.Id) FROM DivisionOrders DivO WHERE DivO.OrderDate BETWEEN MTPDet.FromDate AND MTPDet.ToDate AND DivO.SalesRepresentativeId = MTP.UserId) + --COUNT cannot return 0, so no need for ISNULL
(SELECT Count(DisO.Id) FROM DistributorOrders DisO WHERE DivO.OrderDate BETWEEN MTPDet.FromDate AND MTPDet.ToDate AND DisO.SalesRepresentativeId = MTP.UserId) AS ProductiveVisit,
MTPVM.Remark
from dbo.MTPMaster MTP
JOIN dbo.UserMaster UMc ON MTP.CreatedBy = UMc.id
JOIN dbo.UserMaster UMse ON MTP.UserId = UMse.Id
JOIN MTPDetails MTPDet ON MTP.Id=MTPDet.MTPId
--Inner Join MTPDetailsStatusHistory MtpDetStHistory ON MTPDet.Id=MtpDetStHistory.MTPDetailsId --This is never reference, so I doubt it's needed.
CROSS APPLY (SELECT TOP (1)
RM.[Name]
FROM dbo.MTPDetailsStatusHistory MDSH
JOIN dbo.RouteMaster RM ON MDSH.RouteId = RM.Id
WHERE RM.IsActiveRoute = 1 --Guessed Alias
AND MDSH.MTPDetailsId = MTPDet.Id --Guessed Alias
ORDER BY MDSH.Id DESC) RN
JOIN dbo.MTPVisitMaster MTPVM ON MTPDet.Id = MTPVM.MTPDetailsId
--Below is a guess, as a subquery, in a subquery in a subquery is just a mess I'm afraid. I suspect it's a 1 to 1 relationship
JOIN dbo.UserHQ UHQ ON UMse.id = UGW.Userid
JOIN dbo.HQMaster HQM ON UGW.HQId = HQM.id
WHERE UMse.IsDeleted = 0
AND HQM.DivisionId = 19
GROUP BY UMse.[Name],
MTPDet.FromDate,
MTPDet.ToDate,
UMc.[Name],
RN.[Name],
MTPVM.Distance
MTPVM.Remark;
Примечание. У меня предполагается все ваши объекты находятся в схеме dbo
.