CREATE PROCEDURE [dbo].[BillingCommonReportAllUsers] @ProjectID int = null, @date1 datetime, @date2 datetime AS -- проверяем чтобы даты не были больше текущей if (@date2 > GETDATE()) set @date2 = GETDATE() if (@date2 < @date1) return -- временная табличка для результатов create table #bcru_results ( [UserID] int, [UserName] varchar(100), [WorkTime] int, [InterviewCount] int, [InterviewTime] int, [SuccessInterviewCount] int, [SuccessInterviewTime] int ) -- выбираем всех юзеров, у которых были сессии пересекающиеся с заданным диапазоном -- если сессия ещё не закрыта - тоже считаем declare users cursor local static forward_only for select [UserID], (select [FIO] from [Users] where [ID] = b.[UserID]) as [UserName] from [Billing] b where [EventTypeID] = 10 and ([PeriodDT1] < @date2 and ([PeriodDT2] is null or [PeriodDT2] > @date1)) group by [UserID] order by [UserName] open users set nocount on -- обрабатываем всех юзеров последовательно while 1=1 begin declare @userid int declare @username varchar(100) fetch next from users into @userid, @username if @@FETCH_STATUS <> 0 break declare @worktime int declare @interviewcount int declare @interviewtime int declare @successinterviewcount int declare @successinterviewtime int -- считаем общее рабочее время execute [BillingCalculateTime] 1, @userid, @projectid, @date1, @date2, @worktime output, 0 -- считаем время всех интервью execute [BillingCalculateTime] 2, @userid, @projectid, @date1, @date2, @interviewtime output, 0 -- считаем время полных интервью execute [BillingCalculateTime] 3, @userid, @projectid, @date1, @date2, @successinterviewtime output, 0 -- считаем кол-во интервью execute [BillingCalculateInterview] @userid, @projectid, @date1, @date2, @interviewcount output, @successinterviewcount output -- добавляем результат insert into #bcru_results values (@userid, @username, @worktime, @interviewcount, @interviewtime, @successinterviewcount, @successinterviewtime) end close users deallocate users select * from #bcru_results drop table #bcru_results set nocount off