您可以提取 DateTime 的日期部分并按 UserName 分组以在 MIN / MAX 值上使用 DateDiff:
表和数据设置:
create table UserLog (Username nvarchar(50), LogDate DateTime);
insert into UserLog Values('Test1', '2012-01-01 00:00:00');
insert into UserLog Values('Test2', '2012-01-01 00:00:02');
insert into UserLog Values('Test1', '2012-01-01 00:00:05');
insert into UserLog Values('Test3', '2012-01-01 00:00:06');
insert into UserLog Values('Test3', '2012-01-01 00:01:26');
insert into UserLog Values('Test3', '2012-01-01 00:03:22');
insert into UserLog Values('Test3', '2012-01-01 00:05:42');
insert into UserLog Values('Test3', '2012-01-01 00:00:06');
insert into UserLog Values('Test1', '2012-01-02 00:01:01');
insert into UserLog Values('Test2', '2012-01-02 00:02:50');
insert into UserLog Values('Test1', '2012-01-02 00:01:01');
然后你可以选择如下:
select UserName, CAST(LogDate AS DATE) as BusinessDay,
MIN(LogDate) as FirstLogEntry, MAX(LogDate) as LastLogEntry,
DATEDIFF(second,MIN(LogDate), MAX(LogDate)) as ElapsedSeconds
FROM UserLog
GROUP BY Username, CAST(LogDate AS DATE)
这将产生以下结果,您可以从秒计算小时数。我根据您的示例数据显示了几秒钟,并扩展了 test3 用户:
UserName BusinessDay FirstLogEntry LastLogEntry ElapsedSeconds
-------- ----------- ----------------------- ----------------------- --------------
Test1 2012-01-01 2012-01-01 00:00:00.000 2012-01-01 00:00:05.000 5
Test2 2012-01-01 2012-01-01 00:00:02.000 2012-01-01 00:00:02.000 0
Test3 2012-01-01 2012-01-01 00:00:06.000 2012-01-01 00:05:42.000 336
Test1 2012-01-02 2012-01-02 00:01:01.000 2012-01-02 00:01:01.000 0
Test2 2012-01-02 2012-01-02 00:02:50.000 2012-01-02 00:02:50.000 0