34,594
社区成员
发帖
与我相关
我的任务
分享
create table #t(userID int,stopstarttime datetime,stopendtime datetime,)
insert into #t
select 1,'2019-07-01 14:49:55.130','2019-07-01 14:50:37.903' union all
select 1,'2019-07-01 14:50:42.717','2019-07-01 14:52:07.670' union all
select 1,'2019-07-01 14:52:17.160','2019-07-01 14:52:19.880' union all
select 1,'2019-07-01 14:52:23.523','2019-07-01 15:01:13.510' union all
select 1,'2019-07-01 14:28:41.997','2019-07-01 14:28:48.410' union all
select 1,'2019-07-01 14:29:00.307','2019-07-01 14:49:43.390' union all
select 2,'2019-07-01 14:29:55.470','2019-07-01 14:31:14.657' union all
select 2,'2019-07-01 14:31:59.673','2019-07-01 14:35:00.807' union all
select 2,'2019-06-01 14:35:32.280','2019-07-01 14:41:14.110' -- 此处特意写06/01,以便测试小时计数.
select userID,
dt=rtrim((dt1+cast(left(dt2,2) as int)))+'小时'+substring(dt2,4,2)+'分'+substring(dt2,7,2)+'秒'
from (
select userID,
dt1=sum(datediff(dd,stopstarttime,stopendtime)*24),
dt2=convert(varchar,
dateadd(ms,
sum(datediff(ms,'00:00:00.000',cast(convert(varchar,stopendtime-stopstarttime,114) as time))),'1900-01-01 00:00:00.000'),
114)
from #t
group by userID) t
/*
userID dt
----------- ----------------------------
1 0小时31分49秒
2 720小时10分02秒
(2 行受影响)
*/
SELECT USERID,CAST(SUM(DATEDIFF(HH,STOPSTARTTIME,STOPENDTIME)) AS VARCHAR)+'小时'
+CAST(SUM(DATEDIFF(MINUTE,STOPSTARTTIME,STOPENDTIME)) AS VARCHAR)+'分钟'
+CAST(SUM(DATEDIFF(SECOND,STOPSTARTTIME,STOPENDTIME)) AS VARCHAR)+'秒'
FROM TABLE
GROUP BY USERID
SELECT USERID,CAST(TOTAL/3600 AS VARCHAR)+'小时'+CAST((TOTAL%3600)/60 AS VARCHAR)+'分钟'+CAST((TOTAL%3600)%60 AS VARCHAR)+'秒'
FROM
(SELECT USERID,SUM(DATEDIFF(SECOND,STOPSTARTTIME,STOPENDTIME)) AS TOTAL
FROM TABLE
GROUP BY USERID) AS A