GETTING THE AVERAGE OF TIME

Hi,I have the following code which returns day of week name, position and date and time of surgeries.

SELECT

DATENAME(WEEKDAY,OPE_START_TIME) AS DOW,
[OPE_ORDER_IN_SESS_ASC] AS POSITION,
OPE_START_TIME AS [TIME]

FROM table1

The data looks like this

How can i group this data so I get the average start time by day of week and position?

April 29th, 2015 10:43pm

try this

\declare @table table(c1 varchar(20),c2 int,c3 datetime2(0))
insert into @table
values('monday',1,'2015-04-29 02:09:42')
,('monday',1,'2015-04-29 02:05:42'),
('tuesday',1,'2015-04-29 02:59:42')
,('tuesday',2,'2015-04-29 02:55:42')

;with cte as (select avg(datepart(second,c3)+((datepart(minute,c3)+(datepart(hour,c3)*60))*60)) as c3
,c2,c1 from @table
group by c1,c2)

select right('0'+cast(c3/3600 as varchar),2)+':'+right('0'+cast((c3%3600)/60 as varchar),2)
+':'+right('0'+cast((c3%3600)%60 as varchar),2) as [AvgTime],c2,c1 from cte

Free Windows Admin Tool Kit Click here and download it now
April 29th, 2015 11:18pm

One method:

WITH 
	StartTimes AS (
		SELECT 
			  DATENAME(WEEKDAY,OPE_START_TIME) AS DOW
			, OPE_ORDER_IN_SESS_ASC AS POSITION
			, DATEDIFF(second, '', CAST(OPE_START_TIME AS time)) AS StartTimeSeconds
		FROM dbo.table1
	)
SELECT
	  DOW
	, POSITION
	, DATEADD(second, AVG(StartTimeSeconds), CAST('' AS Time)) AS AvgStartTime
FROM StartTimes
GROUP BY
	  DOW
	, POSITION;

April 29th, 2015 11:31pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics