SELECT
s.ColID1
,s.ColIdentification2
,s.StatusColumn
,(SELECT
MAX(pd.DateColumn)
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'TextFiles')
AS maxDate
,(SELECT TOP 1
u.Title
FROM DocumentTable pd
LEFT OUTER JOIN [User] u
ON u.UserId = pd.UserId
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'Text Files'
ORDER BY pd.DateColumn DESC)
AS Name1
,(SELECT TOP 1
pd.DocumentType
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'Text Files'
ORDER BY pd.DateColumn DESC)
, (SELECT TOP 1
pd.TypeofFile
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'Text Files'
ORDER BY pd.DateColumn DESC)
,(SELECT TOP 1
pd.Region
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'Text Files'
ORDER BY pd.DateColumn DESC)
,(SELECT TOP 1
pd.Agency
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile = 'Text Files'
ORDER BY pd.DateColumn DESC)
FROM Service s (NOLOCK)
--left outer join DocumentTable pd1 (NOLOCK)
--on pd1.ColIdentification2 = s.ColIdentification2
WHERE s.IsPresent = 1
--AND pd1.ColIdentification2 = s.ColIdentification2
AND s.StatusColumn IN ('Val1', 'Val3')
AND NOT EXISTS (SELECT
pd.DocumentTableId
FROM DocumentTable pd
WHERE pd.IsPresent = 1
AND pd.ColIdentification2 = s.ColIdentification2
AND pd.TypeofFile IN ('DC1', 'DC2'))
AND NOT EXISTS (SELECT
utds.ID
FROM utds
WHERE utds.Service_x0020_ID1_Id = s.ColID1
AND utds.Type IN ('DC1', 'DC2'))
ORDER BY s.ColID1
我想優化這個SQL。由於許多子查詢,它需要很長時間。這個查詢花費了超過10分鐘的時間,我正在努力改進它。無論如何避免子查詢。我曾嘗試在表格之間使用左外連接,但我認爲由於文檔表格中ColID1的數據重複,我沒有得到正確的數據處理SQL問題的時間量
謝謝,我們有colIdentification2字段指定爲主鍵與聚集索引就可以了。 。我將嘗試在文檔表上的此列上創建非聚集索引。我同意你的觀點,我會用統計數據來建立。結果集是不同的,當我上次嘗試離開外連接時。 ,但我會嘗試與你的建議 – Nate