Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Average Time from timestamp stored as string

I have two columns called date and starthour in a Microsoft SQL Server table.

Both columns are char; Another guy make it and I don't know why it was built in this way. :)

date                     starthour

20/01/2011               8:10:00
20/01/2011               8:20:00
20/01/2011               8:30:00
20/01/2011               8:40:00
21/01/2011               8:10:00
21/01/2011               8:20:00
21/01/2011               8:30:00

I want to determine the average starthour for each date.

date                     starthour
20/01/2011               8:25:00
21/01/2011               8:20:00

I tried the following:

SELECT date, Avg(cast(starhour as datetime())) AS starhour
FROM table
GROUP BY date

but it doesn't work.

like image 365
Luis Cabanillas Avatar asked Dec 05 '25 15:12

Luis Cabanillas


1 Answers

SELECT [date], 
  CAST(DATEADD(second, AVG(DATEDIFF(second, 0 , starhour)), '00:00:00') AS time)
FROM dbo.test17
GROUP BY [date]

Demo on SQLFiddle

like image 141
Aleksandr Fedorenko Avatar answered Dec 07 '25 07:12

Aleksandr Fedorenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!