-2

I have a date column called OrderDate that I use to track insert time.

It will look like this:

enter image description here

I need to be able to use this OrderDate column and get the average inserts per second. So for example there are 3 inserts per minute happening.

How can I use the datetime column and a create a SQL query that will determine the average inserts per minute?

I have tried to Rollup but this is not giving me what I need.

SELECT      
    YEAR(orderdate)  AS YEAR,
    MONTH(orderdate) AS MONTH,
    DAY(orderdate)   AS DAY,
    DATEPART(hour, orderdate)   AS HOUR,
    DATEPART(MINUTE, orderdate) AS MINUTE,
    DATEPART(SECOND, orderdate) AS SECOND
FROM 
    Sales.Orders
GROUP BY 
    ROLLUP (YEAR(orderdate), MONTH(orderdate), DAY(orderdate), 
            DATEPART(HOUR, orderdate),
            DATEPART(MINUTE, orderdate),
            DATEPART(SECOND, orderdate))   
CodeMan03
  • 570
  • 3
  • 18
  • 43

1 Answers1

0

use lag to get the prior insertdatetime and datepart to get the second interval

declare @temp as table(AccountNumber int, InsertDateTime datetime)

insert into @temp values(59000,'11/1/2021 1:00:01');
insert into @temp values(59000,'11/1/2021 1:00:03');
insert into @temp values(59000,'11/1/2021 1:00:35');
insert into @temp values(59000,'11/1/2021 1:01:03');
insert into @temp values(59000,'11/1/2021 1:01:04');
insert into @temp values(59000,'11/1/2021 1:01:05');
insert into @temp values(59000,'11/1/2021 1:01:06');

with cte
as
(
  select PriorInsertDateTime,
  InsertDateTime,
  IsNull(DateDiff(second,PriorInsertDateTime,InsertDateTime),0) Duration
  from
  (
  select 
  lag(InsertDateTime,1) over(partition by AccountNumber order by InsertDateTime) 
   PriorInsertDateTime,
   InsertDateTime
   from @temp
   )x
)
select avg(Duration) avg_seconds from cte

output

9 seconds

second durations 0,2,32,28,1,1,1,1

Golden Lion
  • 3,840
  • 2
  • 26
  • 35