Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mauris
Starting Member
2 Posts |
Posted - 2010-10-26 : 06:21:39
|
| Hi all,I have a table that acts like an event log, like this:TIME EVENT USER00:00 LOGIN JOE00:04 LOGIN PAUL00:10 LOGUT JOE00:20 LOGIN JOE00:30 LOGIN ANDREW00:32 LOGUT PAUL00:35 LOGUT JOE00:40 LOGOUT ANDREWI want to setup one query in order to have one record for each logged session, like this:USER FROM TOJOE 00:00 00:10PAUL 00:04 00:32JOE 00:20 00:35ANDREW 00:30 00:40My problem is to make into relation each login record with the corresponding logout record. They have the same user in common (of course) but the logut record should be identified like "the first logut record of the same user after his login".Can anyone help me to setup such query?Thank you very muchmaurizio |
|
|
Sachin.Nand
2937 Posts |
Posted - 2010-10-26 : 07:35:23
|
| [code]declare @t table(TIME varchar(20), EVENT varchar(20), [USER] varchar(20))insert @tselect '00:00','LOGIN' ,'JOE' unionselect '00:04','LOGIN','PAUL' unionselect '00:10', 'LOGOUT','JOE' unionselect '00:20', 'LOGIN','JOE' unionselect '00:30', 'LOGIN','ANDREW' unionselect '00:32', 'LOGOUT','PAUL' unionselect '00:35', 'LOGOUT','JOE' unionselect '00:40', 'LOGOUT', 'ANDREW';with cteas(select *,ROW_NUMBER()over(partition by event,user order by user,time)rid from @t)select * from(select [USER] [User],TIME Intime,Outtime from cte c1cross apply(select top 1 TIME as outtime from cte c2 where c1.[USER]=c2.[USER] and c1.rid=c2.rid and c1.EVENT<>c2.EVENT)C)t where intime<>outtime and outtime>intime[/code]PBUH |
 |
|
|
mauris
Starting Member
2 Posts |
Posted - 2010-10-28 : 08:34:39
|
quote: Originally posted by Sachin.Nand
declare @t table(TIME varchar(20), EVENT varchar(20), [USER] varchar(20))insert @t ...
Hi, thank you so much for your (fast )answer.Unfortunately I discovered that I need to run the query under SQL server 2000 and some of your commands (like row_number()) were not supported Have you got another solution ?maurizio |
 |
|
|
|
|
|
|
|