I have this Query. I need a way to optimize this.
SELECT DISTINCT /*First SQL*/
SK.key AS SECURE,
sl.col1 AS Name,
sl.col2 AS Value,
SK.log AS KEYLOG,
SK.time,
(
SELECT max(L.log)
FROM dbo.LogTable AS L
WHERE L.key = SK.key AND L.time < SK.time
) AS PREVIOUS
INTO #temp_prev_both
FROM dbo.LogkeyTbl AS SK, dbo.LogTable AS sl
WHERE
SK.log = sl.log AND
SK.time >= ’11-14-2007 12:00:00 AM’ AND
SK.time <= ’11-14-2007 11:59:59 PM’ AND
SK.time =
(
SELECT max(S.time)
FROM dbo. LogkeyTbl AS S, dbo. LogTable AS sl
WHERE
S.log = sl.log AND
S.Key = SK.Key AND
S.time >= ’11-14-2007 12:00:00 AM’ AND
S.time <= ’11-14-2007 11:59:59 PM’
GROUP BY S.Key
)
ORDER BY 1
SELECT * /*Second SQL*/
FROM #temp_prev_both t left outer join LogTable sl ON t.Previous = sl.log and t.Name = sl.Name
First SQL command will dump all the records to a temp table. There are approx 400K records.
Second SQL is taking 7 mins to run.
Is there any way to reduce the time of running?
SELECT DISTINCT /*First SQL*/
SK.key AS SECURE,
sl.col1 AS Name,
sl.col2 AS Value,
SK.log AS KEYLOG,
SK.time,
(
SELECT max(L.log)
FROM dbo.LogTable AS L
WHERE L.key = SK.key AND L.time < SK.time
) AS PREVIOUS
INTO #temp_prev_both
FROM dbo.LogkeyTbl AS SK, dbo.LogTable AS sl
WHERE
SK.log = sl.log AND
SK.time >= ’11-14-2007 12:00:00 AM’ AND
SK.time <= ’11-14-2007 11:59:59 PM’ AND
SK.time =
(
SELECT max(S.time)
FROM dbo. LogkeyTbl AS S, dbo. LogTable AS sl
WHERE
S.log = sl.log AND
S.Key = SK.Key AND
S.time >= ’11-14-2007 12:00:00 AM’ AND
S.time <= ’11-14-2007 11:59:59 PM’
GROUP BY S.Key
)
ORDER BY 1
SELECT * /*Second SQL*/
FROM #temp_prev_both t left outer join LogTable sl ON t.Previous = sl.log and t.Name = sl.Name
First SQL command will dump all the records to a temp table. There are approx 400K records.
Second SQL is taking 7 mins to run.
Is there any way to reduce the time of running?