我想获得用户的活动时间..
他是什么时候离开的,他什么时候回来的,他离开了多少时间表格看起来像这样..
id deviceid time status
11 123-123 09:59 1
12 123-123 10:00 0
13 123-123 10:02 0
14 123-123 10:03 0
15 123-123 10:04 0
16 123-123 10:05 1
10点他离开了...在10:05他回到网上..我想计算他离开时的时间..
编辑:
status = 0表示用户离开.. status = 1表示他在线..
答案 0 :(得分:1)
听起来你正在寻求解决方案。这真是太好了。通过解决具有挑战性的问题,我们都学到了最多。只是为了好玩(我在项目之间有几分钟)我把一个工作的例子扔在一起。我添加了一些额外的样本数据,并注明了这一点。
我从杰夫莫登那里学到了这种东西。他在这里有一篇关于它的文章。 http://www.sqlservercentral.com/articles/T-SQL/71550/
if OBJECT_ID('tempdb..#Something') is not null
drop table #Something
create table #Something
(
ID int
, deviceid varchar(10)
, StatusTime time
, IsOnline bit
)
insert #Something
select 11, '123-123', '09:59', 1 union all
select 12, '123-123', '10:00', 0 union all --added by me
select 12, '123-123', '10:01', 0 union all
select 13, '123-123', '10:02', 0 union all
select 14, '123-123', '10:03', 0 union all
select 15, '123-123', '10:04', 0 union all
select 16, '123-123', '10:05', 1
-- added some extra data here to simulate multiple groups
union all
select 17, '123-123', '10:06', 0 union all
select 18, '123-123', '10:07', 0 union all
select 19, '123-123', '10:08', 0 union all
select 20, '123-123', '10:09', 1 union all
select 21, '123-123', '10:10', 0 --This demonstrates that if the last value is away it will still count it as 1
;
with GroupedDates as
(
select
*
, DATEADD(minute, - ROW_NUMBER() over(partition by deviceid order by StatusTime), StatusTime) as DateGroup
from #Something
where IsOnline = 0
)
select MIN(StatusTime) as StartTime
, MAX(StatusTime) as EndTime
, DATEDIFF(Minute, MIN(StatusTime), MAX(StatusTime)) + 1 as MinutesAway
from GroupedDates
group by DateGroup