天数总和

时间:2013-10-03 13:51:29

标签: sql sql-server vb.net tsql

这些是我的表格字段

 AtdId  MCId    AtdDate              CheckIn                CheckOut            Status
    675 7   2013-10-03  2013-10-03 16:42:49.307         2013-10-03 16:43:10.317 0#0#56
    676 7   2013-10-03  2013-10-03 16:46:28.730         2013-10-03 16:46:35.780 0#0#7
    677 7   2013-10-03  2013-10-03 16:49:33.190     2013-10-03 16:49:35.140 0#0#2
    678 7   2013-10-03  2013-10-03 16:49:36.913         2013-10-03 16:49:38.377 0#0#2
    679 7   2013-10-03  2013-10-03 16:49:39.397     2013-10-03 16:49:40.023 0#0#1
    680 7   2013-10-03  2013-10-03 16:49:41.043         2013-10-03 16:49:41.703 0#0#0
    681 7   2013-10-03  2013-10-03 16:49:43.307         2013-10-03 16:49:45.063 0#0#2
    682 7   2013-10-03  2013-10-03 16:50:33.657         2013-10-03 16:50:45.783 0#0#12
    683 7   2013-10-03  2013-10-03 16:51:35.007         2013-10-03 16:52:42.877 0#1#7

状态字段0#0#0是小时#分钟#秒。我怎样才能将每日小时和秒的总和显示为明确的总持续时间? 状态是db中的varchar,我正在使用MSSQL。

1 个答案:

答案 0 :(得分:2)

我仍然认为从CheckIn和CheckOut列中提取SUM更好。但是,如果你想从状态中获取SUM,这是一种方法。

WITH cte AS (
  SELECT 
    *,
    PARSENAME(REPLACE(Status,'#','.'), 1) AS StatusSecond,
    PARSENAME(REPLACE(Status,'#','.'),2) AS StatusMinute,
    PARSENAME(REPLACE(Status,'#','.'),3) AS StatusHour
  FROM tbl
)
SELECT [AtdDate], SUM(StatusHour*60*60 +  StatusMinute * 60 + StatusSecond) AS TotalTimeInSecond
FROM cte  
GROUP BY [AtdDate]
ORDER BY [AtdDate]

sql fiddle demo

修改

要过滤当前日/周/月,您可以在上面的查询中添加以下条件。

WHERE DATEDIFF(week,AtdDate,GETDATE()) = 0 
-- You can change week to Day or Month 

更多Deails,请参阅DATEDIFF