How to Split Time and calculate time difference in sql server 2005?

你。 提交于 2020-01-03 03:01:50

问题


i want to split the time and calculate time difference using sql server 2005

my default output is like this:

EnrollNo     AttDateFirst                          AttDateLast
111      2011-12-09 08:46:00.000          2011-12-09 08:46:00.000
112      2011-12-09 08:40:00.000          2011-12-09 17:30:00.000
302      2011-12-09 09:00:00.000          2011-12-09 18:30:00.000
303      2011-12-09 10:00:00.000          2011-12-09 18:35:00.000

I want my new output to be like this:

Enroll No     .....      FirtTime       LastTime      Time Diff
111           .....      8:46:00          8:45:00     00:00:00
112           .....      8:30:00         17:30:00      9:00:00
302           .....      9:00:00         18:30:00      9:30:00 
303           .....     10:00:00         18:35:00      8:35:00

回答1:


You can use this query:

select EnrollNo, convert(varchar, AttDateFirst, 8) as FirstTime,
                 convert(varchar, AttDateLast, 8) as LastTime,
                 convert(varchar, AttDateLast - AttDateFirst, 8) as [Time Diff]
from YourTable

to return the following results:

EnrollNo    FirstTime                      LastTime                       Time Diff
----------- ------------------------------ ------------------------------ ------------------------------
111         08:46:00                       08:46:00                       00:00:00
112         08:30:00                       17:30:00                       09:00:00
302         09:00:00                       18:30:00                       09:30:00
303         10:00:00                       18:35:00                       08:35:00



回答2:


you can use

select DATEDIFF(day,2007-11-30,2007-11-20) AS NumberOfDays, DATEDIFF(hour,2007-11-30,2007-11-20) AS NumberOfHours, DATEDIFF(minute,2007-11-30,2007-11-20) AS NumberOfMinutes from test_table

to split u can use

substring(AttDateFirst,charindex(' ',AttDateFirst)+1 ,
                       len(AttDateFirst)) as [FirstTime]


来源:https://stackoverflow.com/questions/7721984/how-to-split-time-and-calculate-time-difference-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!