简体   繁体   中英

Slow TSQL query with nested selects

I have written a query, but appears to run quite slowly in our live environment. The query contains nested select statements which I believe to slow down execution.

Does anyone have any tips of how I could re-write the query to improve the execution speed.

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

SET @StartDate = '20140101'
SET @EndDate = '20140101'

SELECT a.applicationid,
       a.ourreference,
       (SELECT MAX(e.CreateDateTime) FROM tblEmail AS e WHERE( e.ApplicationID = a.ApplicationID) AND (ISNULL(e.StandardEmailID,0) <> 3)) AS 'LastEmail',
       (SELECT MAX(l.CreateDateTime) FROM tblLetter AS l WHERE l.ApplicationID = a.ApplicationID AND l.ExternalDocumentTypeID IS NULL) AS 'LastInternalLetter',
       (SELECT MAX(l.CreateDateTime) FROM tblLetter AS l WHERE l.ApplicationID = a.ApplicationID AND l.ExternalDocumentTypeID IS NOT NULL) AS 'LastExternalLetter'
INTO #Temp
FROM tblapplication AS a
WHERE (a.LogDate BETWEEN @StartDate AND @EndDate + '23:59:59')
AND (a.BusinessSourceID NOT IN (11, 16))
AND (a.ApplicationStatusID = 100)

SELECT *
FROM #Temp AS tem
WHERE ((LastEmail < LastExternalLetter) AND (LastInternalLetter < LastExternalLetter))

Cheers everyone

edit- Sorry I should say what the query is for. I am trying to see if our customers have sent us a letter and we haven't responded to them with a letter/email

select *
from
(
    Select a.applicationId, a.ourreference,
           max(e.CreateDateTime) LastEmail,
           max(li.CreateDateTime) LastInternalLetter,
           max(le.CreateDateTime) LastExternalLetter
    from tblApplication a
    left outer join tblEmail e on e.ApplicationID = a.ApplicationID 
    left outer join tblLetter li on li.ApplicationId = a.ApplicationId
    left outer join tblLetter le on le.ApplicationId = a.ApplicationId
    WHERE (a.LogDate BETWEEN @StartDate AND @EndDate + '23:59:59')
    AND (a.BusinessSourceID NOT IN (11, 16))
    AND (a.ApplicationStatusID = 100)
    and (e.StandardEmailID <> 3 or e.StandardEmailId is null)
    group by a.ApplicationId, a.OurReference
)x
WHERE ((LastEmail < LastExternalLetter) AND (LastInternalLetter < LastExternalLetter))

This gets rid of the temporary table. Remember, with SQL wherever you have a Table you can substitute a query (in Selects anyway). This should make it a bit more efficient, but you want to look at the Query Plans and see what's holding it up.

Cheers -

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