SQL Server 2005中DateTime数据集的平均时间

时间:2010-10-04 18:33:08

标签: sql-server-2005 datetime average

我正在努力获得平均每个客户完成交付停止的平均时间。我使用以下列:

Name (varchar(50))
Reference1 (varchar(50))
CompletedTime (Datetime).

我得到一个平均但它包括日期&时间不仅仅是约会。这使得时间平均不正确。

感谢您的帮助!

当前代码:

select name, Reference1, CAST(AVG(CAST(CompletedTime AS float)) AS datetime)
From tblOrderRouteStops
where Name not like 'Cta%' and Reference1 <> '000000' and Name <> '' and CompletedTime is not Null
Group By name, Reference1

数据集:

CASCADE HEMOPHILIA CONSORTIUM   000117  2010-10-01 09:24:01.000
CASCADE HEMOPHILIA CONSORTIUM   000117  2010-09-29 09:30:23.000
CASCADE HEMOPHILIA CONSORTIUM   000117  2010-09-27 09:44:17.000
CASCADE HEMOPHILIA CONSORTIUM   000117  2010-09-24 09:36:49.000
CASCADE HEMOPHILIA CONSORTIUM   000117  2010-09-23 09:48:20.000
CASCADE HEMOPHILIA CONSORTIUM   000117  2010-09-22 09:21:20.000
BOTSFORD OUT-PATIENT PHARMACY   006106  2010-09-23 08:01:06.000
BOTSFORD OUT-PATIENT PHARMACY   006106  2010-09-22 08:02:42.000
BOTSFORD OUT-PATIENT PHARMACY   006106  2010-09-24 08:21:36.000
BOTSFORD OUT-PATIENT PHARMACY   006106  2010-09-27 08:24:49.000
BOTSFORD OUT-PATIENT PHARMACY   006106  2010-09-28 08:25:58.000
BOTSFORD GENERAL HOSPITAL PREM  006205  2010-10-04 07:33:13.000
BOTSFORD GENERAL HOSPITAL PREM  006205  2010-10-01 07:35:13.000
BOTSFORD GENERAL HOSPITAL PREM  006205  2010-09-30 07:31:15.000
BOTSFORD GENERAL HOSPITAL PREM  006205  2010-09-29 07:41:56.000
BOTSFORD GENERAL HOSPITAL PREM  006205  2010-09-28 08:03:38.000

期望输出:

Name, Reference1, Time

2 个答案:

答案 0 :(得分:3)

你的浮动方法是一个好的开始:你需要删除整数,它给你一个代表时间的分数。平均值,改回日期时间。要使用此功能,请忽略“01 jan 1900”并将时间位作为平均值

select name, Reference1,
          CAST(AVG(CAST(CompletedTime AS float) - CAST(CompletedTime AS int)) AS datetime)
From tblOrderRouteStops
where Name not like 'Cta%' and Reference1 <> '000000' and Name <> '' and CompletedTime is not Null
Group By name, Reference1

答案 1 :(得分:0)

这将为你工作

你可以使用convert(varchar,Value,108)

来摆脱日期
select name, Reference1,
    CONVERT(varchar,  CAST(AVG(CAST(CompletedTime AS float) - CAST(CompletedTime AS int)) AS datetime),108) averageTime
        From tblOrderRouteStops
        where Name not like 'Cta%' and Reference1 <> '000000' and Name <> '' and CompletedTime is not Null
        Group By name, Reference1