Rewriting Outer apply to join for performance

Multi tool use
Multi tool use


Rewriting Outer apply to join for performance



Since I am not that familiar with Outer Apply, I am a bit lost with rewriting the one from my previous question to join. It worked well but not for large chunks of data. Any help with this appreciated.



Previous question





Which version of sql server (please tag your questions appropriately)? Since v2012 we have LEAD() and LAG()
– Shnugo
Jul 2 at 10:33


LEAD()


LAG()





We are using 2008R2
– NihilisticWonder
Jul 2 at 11:00





The APPLY will compute data row-wise while a JOIN will try to connect two sets over a given criterion. In your case - as you want to get the previous entry the row-wise approach looks pretty much okay...
– Shnugo
Jul 2 at 11:10


APPLY


JOIN





Yes it is funcional, but the query is taking far too long to execute, and I need to cut the execution time down as much as I can.
– NihilisticWonder
Jul 2 at 12:22





The approach of the previous question would need indexes on EntryTime and PhoneNumber. Do you have the needed indexes in your database? Are there other processes involved?
– Shnugo
Jul 2 at 16:42




1 Answer
1



You might use the following approach:


CTE


ROW_NUMBER


ROW_NUMBER


OVER()


PARTITION BY


ORDER BY



This will return a list of your phone calls, where each phone number as a consecutive index in the order of EntryTime.


EntryTime



You can then use a self-join to find the corresponding previous row.


declare @table table (
PhoneNumber nvarchar(20),
EntryTime datetime
)

insert into @table values ('(321) 546-7842', dateadd(hour,-30,getdate()));
insert into @table values ('(321) 546-7842', dateadd(hour,-3,getdate()));
insert into @table values ('(251) 546-9442', dateadd(hour,-2,getdate()));

WITH cte AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY PhoneNumber ORDER BY EntryTime) AS CallIndex
,t.*
FROM @table t
)
SELECT *
FROM cte t1
LEFT JOIN cte t2 ON t1.PhoneNumber=t2.PhoneNumber AND t1.CallIndex=t2.CallIndex-1
ORDER BY t1.PhoneNumber, t1.EntryTime;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

fKNb SSYLYZPIkf2M36HHCE1,g5rQyC40GgqjovBABeGOhBfe,aeVjKd1i4nJPRqxN8,qBWaJt8nTHjN2Lppu2LyXUDaVq3 H,jCuP0o
TOqAYztRZTAd,Xx61wZm4,xcO82rlIEJLrJ1API,FC

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications