SQL查询按天分组并计算已用时间(聚合行)

时间:2012-05-07 23:20:24

标签: sql sql-server-2008

我正在使用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相加,并使用相同的用户名按天分组。

我尝试使用等级,但没有得到我想要的东西。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过UserName提取DateTime和group的日期部分,以便在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