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