2011-10-11 32 views
2

我有表的時間列選擇總時間(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語句給您錯誤:

操作數數據類型時間對於添加操作符無效。

回答

1

你可以決定每個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 
-1

我相信你可以使用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

0

試試下面的腳本。

選擇轉換(時間,CONVERT(日期時間,00:08:00.000 ')+ CONVERT(日期時間,00:07:00.000'))

選擇轉換(時間,投('00:08 :00.000'as datetime)+ cast('00:07:00.000'as datetime))'T'

相關問題