I would like to compute a moving average for the last 1 second on each row. The below is only the first part of a way of doing it without a cursor but I left the second part with the average out as this first step is too slow alone. There is a clustered index on copynumber, seqnum, datet and it shows up as 100% clustered index scan. The TOPS's are to shrink the size for testing purposes.The below tries to find the row number of the record that is 1 second or less (but as little less among all records as possible) beforethe current record. The next step which I omitted as it is slow enough already would be to compute the average based on rows preceding. The estimated execution plan says 100% clustered index seek.Dates are datetime2. seqnum and datet are the same order except datet ties.I am looking for the fasted non cursor method preferably without saving a new table/creating a new index. Assume lots of ram and many cores and fast (sequential) spinning disk and sql server enterprise 2012. One idea I just had is to create a list of all the times minus one second along with the existing records, sort them, then join on that as at least I would be testing equality rather than the complex join criteria below (that should only find 1 record FYI given the ordering).--5 minutes run timewith esh as (select TOP 100000 row_number() over (partition by copynumber order by seqnum,datet) as oldrow, lead(datet,1) over (partition by copynumber order by seqnum, datet) as datetp1, lag(datet,1) over (partition by copynumber order by seqnum,datet) as datetm1, * from es10day where copynumber = 1)select top 1000 eso.*, row_number() over (partition by eso.copynumber order by eso.seqnum,eso.datet) as currow from es10day eso left outer join esh on eso.copynumber = esh.copynumber and dateadd(second,-1,eso.datet) <= esh.datet and ( dateadd(second,-1,eso.datet) > esh.datetm1 or esh.datetm1 is null) where eso.copynumber =1
↧