浮动为DateTime

时间:2010-05-12 20:33:16

标签: sql-server sql-server-2008

SQL Server 2008

我认为,我几乎要做的事情。我只想微调结果。我有一个表存储系统上发生的所有事务的时间戳。我正在写一个查询来给出平均交易时间。这就是我到目前为止所做的:

With TransTime AS (
  select endtime-starttime AS Totaltime 
    from transactiontime
   where starttime > '2010-05-12' and endtime < '2010-05-13')
Select CAST(AVG(CAST(TotalTime As Float))As Datetime) 
  from TransTime

我得到以下结果:

1900-01-01 00:00:00.007

我无法弄清楚如何剥离日期并只显示时间00:00:00:007。任何帮助,将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:4)

您想要投射为TIME

With TransTime AS (
  select endtime-starttime AS Totaltime 
    from transactiontime
   where starttime > '2010-05-12' and endtime < '2010-05-13')
Select CAST(AVG(CAST(TotalTime As Float))As TIME(7)) 
  from TransTime

答案 1 :(得分:1)

这是第一次减法,这是你的问题,为什么你把结果投到DATETIME(甚至是TIME)?

With TransTime AS 
(
    -- get time in milliseconds
    select DATEDIFF(ms, starttime, endtime) AS Totaltime 
        from transactiontime
        where starttime > '2010-05-12' and endtime < '2010-05-13'
)
Select AVG(CAST(TotalTime As Float)) AS average_time_in_msec
    FROM TransTime

答案 2 :(得分:0)

您可能希望使用DATEPART函数执行此操作。查看文档here