1

我正在使用 SQL Server 2008 并查看如何创建这样的查询:

我有一张桌子:

Username nvarchar(50), LogDate datetime

Test1, 2012.01.01 00:00:00
Test2, 2012.01.01 00:00:02
Test1, 2012.01.01 00:00:05
Test3, 2012.01.01 00:00:06
Test1, 2012.01.02 00:01:01
Test2, 2012.01.02 00:02:50
Test1, 2012.01.02 00:01:01

每隔几秒钟,用户就会发送更新以将当前日期时间及其用户名插入到日志表中。我需要计算用户每天“在线”的时间。

我假设查询应该对具有相同用户名的两行之间的 DateDiff 求和,并按天分组。

我尝试使用排名,但没有得到我想要的。

提前谢谢你的帮助。

4

1 回答 1

1

您可以提取 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
于 2012-05-08T01:58:22.160 回答