如何从三个时间列(SQL Server 2008中)

问题描述:

我有表的时间列选择总时间(0)数据类型:如何从三个时间列(SQL Server 2008中)

Name TimeOne   TimeTwo   TimeThree 
------ ---------------- ---------------- ---------------- 
Sarah 06:45:00   03:30:00   NULL 
John 06:45:00   NULL    NULL 

如何使SELECT语句,使“CalculatedTotal”列是从TimeOne,TimeTwo和TimeThree每行?

我想吃点什么是选择查询这样的:

SELECT 
    Name, 
    TimeOne, 
    TimeTwo, 
    TimeThree, 
    TimeOne + TimeTwo + TimeThree As CalculatedTotal 
FROM 
    MyTable 

我想找回结果集是这样的:

Name TimeOne   TimeTwo   TimeThree  CalculatedTotal 
------ ---------------- ---------------- ---------------- --------------- 
Sarah 06:45:00   03:30:00   NULL    10:15:00 
John 06:45:00   NULL    NULL    06:45:00 

只需使用加运算符在SELECT语句给您错误:

操作数数据类型时间对于添加操作符无效。

你可以决定每个time值的秒数,它们相加,并转换回time

select TimeOne, TimeTwo, TimeThree, 
     cast(dateadd(s, isnull(datediff(s, 0, TimeOne), 0) + isnull(datediff(s, 0, TimeTwo), 0) + isnull(datediff(s, 0, TimeThree), 0), 0) as time(0)) as CalculatedTotal 
from MyTable 

我相信你可以使用SUM()函数

SELECT 
    Name, 
    TimeOne, 
    TimeTwo, 
    TimeThree, 
    SUM(TimeOne+TimeTwo+TimeThree) As CalculatedTotal 
FROM 
    MyTable 

但同样可能需要每个转换为首先使用第二()函数秒钟,然后对结果使用SEC_TO_TIME()。

编辑:我刚刚看了一下说明书:

The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the values to numbers, which loses the part after the first nonnumeric character.) To work around this problem, you can convert to numeric units, perform the aggregate operation, and convert back to a temporal value. Examples:

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name; 
SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_name; 
+0

不,你不能。你会得到同样的错误。 – 2011-10-11 13:29:06

+0

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(col1)+ TIME_TO_SEC(col2)))as col4 FROM'test' - 显示行0 - 0(总共约11个,查询花费0.0004秒)col4 27:10:34 –

+3

也许if他正在使用MySQL。看看他的标签,它是SQL Server。这不是SQL Server中的功能。 – 2011-10-11 13:42:28

试试下面的脚本。

选择转换(时间,CONVERT(日期时间,00:08:00.000 ')+ CONVERT(日期时间,00:07:00.000'))

选择转换(时间,投('00:08 :00.000'as datetime)+ cast('00:07:00.000'as datetime))'T'