I have a T-SQL query that run during 6 minutes.
There is several sub-query on the same table in it. I think it is the cause of the problem.
But I have no idea for optimizing it.
SELECT dateheure, bac, presence, reponse
,(select top 1 dateheure from LogEvents where bac = t1.bac and dateheure < t1.dateheure order by id desc) as dateheure_precedente
,(select top 1 presence from LogEvents where bac = t1.bac and dateheure < t1.dateheure order by id desc) as presence_precedente
,(select top 1 reponse from LogEvents where bac = t1.bac and dateheure < t1.dateheure order by id desc) as reponse_precedente
,(select top 1 dateheure from LogEvents where bac = t1.bac and dateheure > t1.dateheure order by id asc) as dateheure_suivante
,(select top 1 presence from LogEvents where bac = t1.bac and dateheure > t1.dateheure order by id asc) as presence_suivante
,(select top 1 reponse from LogEvents where bac = t1.bac and dateheure > t1.dateheure order by id asc) as reponse_suivante
FROM [alpla_log].[dbo].[LogEvents] t1
WHERE
t1.presence = 7845
AND DATEFROMPARTS(DATEPART(year,dateheure),DATEPART(month,dateheure),DATEPART(day,dateheure)) = '11/07/2024'
ORDER BY id DESC
I tried to add index on the table but it make no difference.
Can anyone help ?
Thank you
New contributor