简体   繁体   English

从varchar到datetime的SQL转换

[英]SQL conversion from varchar to datetime

One of the columns of my SQL Server table is mm:ss of varchar type where mm = minutes and ss = seconds. 我的SQL Server表的一列是varchar类型的mm:ss ,其中mm =分钟, ss =秒。

I need to get the average of that column. 我需要获取该列的平均值。

Should I convert that column to datetime format first? 我应该先将该列转换为datetime格式吗? If so can you tell me how? 如果可以,您能告诉我如何? If not can you tell me what I should do? 如果不能,您能告诉我该怎么办?

Here is my failed attempt to convert it to datetime : 这是我将其转换为datetime的失败尝试:

SELECT CONVERT(DATETIME, '2014-01-01 '+Pace+':00', 108)

Where pace is a varchar like 23:05 节奏像varchar一样23:05

If you want the average, I would convert the column to number of seconds and work with that: 如果您想要平均值,则可以将该列转换为秒数并使用该值:

select avg(pace_secs) as average_in_seconds
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
      from t
     ) t;

If you want this back in the format, then you can do: 如果您希望将其恢复为格式,则可以执行以下操作:

select right('00' + cast(avg(pace_secs) / 60 as int), 2) + ':' +
       right('00' + avg(page_secs) % 60), 2)
    from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
          from t
         ) t;
declare @pace varchar(20) = '23:05                    ';

SELECT cast( '2014-01-01 '+cast(@pace as varchar(5))+':00' as datetime)

For SQL2012 and later 对于SQL2012及更高版本

SELECT
  FORMAT(DATEADD(second,AVG(DATEDIFF(second,0,'00:'+[Pace])),0),'mm:ss')
FROM MyTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM