M
M
Max2015-06-11 11:58:56
SQL
Max, 2015-06-11 11:58:56

How to select the first login for each user in each day?

Colleagues, good time of day.
I ask for the help of the collective mind =). There is a table with dates, times and username (PC login registration). During the day, 1 user logs on to the network several times - there are several entries with 1 name and 1 date. The table contains data for several days.
The task is to get a list of the first entries in each day for each employee.
I tried to implement it through the cursor (in fact - after 2, by day and by employee) - however, some kind of nonsense is obtained at the output.
DECLARE uName CURSOR FOR Select distinct LTRIM(RTRIM([Name])) AS NAME FROM [OVB].[dbo].[res] ORDER BY NAME
DECLARE @vDate datetime, @vName nvarchar(50)
OPEN uName
FETCH NEXT FROM uName INTO @vName
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE uDate CURSOR FOR Select distinct CONVERT(datetime, LEFT(CONVERT(VARCHAR, [Date], 103), 10)) FROM [OVB].[dbo].[res] WHERE LTRIM(RTRIM([Name]))= @vName
OPEN uDate
WHILE (@@FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM uDate INTO @vDate
INSERT INTO [OVB].[dbo].[PC_LOGIN] SELECT TOP 1 [Date],[Time],[Name] FROM [OVB ].[dbo].[res] WHERE LTRIM(RTRIM([Name]))[email protected] and CONVERT(datetime, LEFT(CONVERT(VARCHAR, [Date], 103), 10))[email protected]
END
CLOSE uDate
DEALLOCATE uDate
FETCH NEXT FROM uName
END
CLOSE uName
DEALLOCATE uName

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2015-06-11
@MaxDukov

Курсоры зло.
begin tran

create table #res (
  ID int not null identity(1, 1),
  [Date] datetime not null,
  Name varchar(100) not null,
  constraint	PKres		primary	key	( Id )
)

insert #res ([Date], Name) values ('20150611 10:00', 'Пупкин')
insert #res ([Date], Name) values ('20150611 12:00', 'Пупкин')
insert #res ([Date], Name) values ('20150611 10:30', 'Иванов')

select dateadd(day, datediff(day, 0, [Date]), 0) [Day], min([Date]) Start, Name
from #res
group by dateadd(day, datediff(day, 0, [Date]), 0), Name
order by min([Date])

rollback

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question