简体   繁体   中英

SQL Query for only one table - takes too much time

I have below sql query.

declare @RoleID int
SELECT @RoleID = RoleID FROM RoleMaster WHERE RoleEnglishDesc = 'Surveyor'

SELECT * FROM (
 SELECT
  S.ShiftID, 2 AS Flag, ISNULL(U.Latitude, 0) Latitude, ISNULL(U.Longitude, 0) Longitude,
  U.EmployeeEnglishName AS ToolTipEnglish, U.EmployeeArabicName AS ToolTipArabic,
  0 AS CaseStageID, COUNT(C.SurveyorAssigned) AS Assigned
  -- L.EntryTime AS LastEntryTime
  -- S1.cnt AS OnBreak
 FROM 
  Users U
   INNER JOIN dbo.SurveyorShift S ON S.UserId = U.UserID AND S.ShiftStatus = 1
   LEFT JOIN CaseInfoCommandQueue C ON C.SurveyorAssigned = U.UserID
 WHERE U.IsActive = 1
  AND NULLIF(NULLIF(U.Latitude, '0'), '') IS NOT NULL
  AND NULLIF(NULLIF(U.Longitude, '0'), '') IS NOT NULL
  AND ((U.RoleID = @RoleID) OR (U.RoleID2 = @RoleID) OR (U.RoleID3 = @RoleID))
 GROUP BY U.UserID, RoleID, Latitude, Longitude, EmployeeEnglishName, EmployeeArabicName, ShiftID
) D
OUTER APPLY 
(
 SELECT TOP 1 EntryTime FROM DeviceUserLocation DLoc
 WHERE DLoc.ShiftID = D.ShiftID ORDER BY DLoc.EntryTime DESC
) AS L

My only problem in last outer apply to fetch entry time. Because that outer apply only takes 10 secs. That table DeviceUserLocation also have lacs of entries. Any overcome or step to use top 1 in other way?

Create covering indexes for your data, make sure you have a clustered index on each table and as above re keys, if you dont know about clustered and covering indexes then here: http://en.wikipedia.org/wiki/Database_index#Covering_index and especially here: https://www.simple-talk.com/sql/learn-sql-server/using-covering-indexes-to-improve-query-performance/ your query is probably doing table scans (searching or examining every row) rather that index lookups: finding a value in an index and going direct to that row. (it cant do an index lookup if there isn't and index on that column, and it can't go direct if there isn't a clustered index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM