苦苦挣扎,获得理想的回报

时间:2015-04-20 23:27:59

标签: mysql left-join

我对SQL比较陌生,但我通常是一个快速学习者,这个特定的查询让我困扰了几天。在这一点上,任何帮助都将无法被欣赏。

当我运行以下查询时,我只返回存在statusdatetime的行(当天登录的代理)。即使代理未登录但已安排,我也需要返回一行。如何更改此查询以返回NULL。我认为左连接会起作用。

DECLARE @startDate datetime
DECLARE @endDate datetime

SET @startDate = GETDATE()
SET @endDate = GETDATE()

SET @startDate = CONVERT(DATETIME, CONVERT(varchar(11),@startDate, 111 ) + ' 00:00:00', 111)
SET @endDate = CONVERT(DATETIME, CONVERT(varchar(11),@endDate, 111 ) + ' 23:59:59', 111)


Begin

Create table #boris5table(
Firstname varchar(50),
lastname varchar (50),
username varchar (50),
starttime datetime,
loggedintime datetime,
variation int)

End


Insert into #boris5table (Firstname, lastname, username, starttime, loggedintime, variation)
Select firstname, lastname, userid,
(cast(DATEADD(MINUTE, (-300 +
(select min(startoffset) from [dbo].[IO_ScheduleInterval]
Where activitytypeid = '0000000000000000000004'
and PaidTime = '1'
and f1.agentid = f2.agentid
and ScheduleID = f1.scheduleid)), StartDateTimeUTC) as datetime)),
case when exists (select count(*), statusdatetime from [dbo].[AgentActivityLog] Where StatusDateTime between @startdate and @enddate Group by StatusDateTime) then min(statusdatetime)
Else NULL
End as LoggedInTime,
DATEDIFF(minute, (cast(DATEADD(MINUTE, (-300 +
(select min(startoffset) from [dbo].[IO_ScheduleInterval]
Where activitytypeid = '0000000000000000000004'
and PaidTime = '1'
and f1.agentid = f2.agentid
and ScheduleID = f1.scheduleid)), StartDateTimeUTC) as datetime)), 

case when exists (select statusdatetime from [dbo].[AgentActivityLog] Where  StatusDateTime between @startdate and @enddate and f3.UserId = f2.UserName) then min(statusdatetime)
Else 'NULL' END)
as 'Variation (minutes)'

From [I3_IC].[dbo].[IO_Schedule] as f1
left join [dbo].[IO_Agent] as f2 on f1.AgentID = f2.AgentID and (CAST(DATEADD(hour, - 5, f1.StartDateTimeUTC) as date)) between @startdate and @enddate
left join [dbo].[Individual] as f4 on f2.UserName = f4.WebLogin and LastName <> '-'
left join [dbo].[AgentActivityLog] as f3 on f2.UserName = f3.UserId and (CAST(DATEADD(hour, -1, f3.StatusDateTime) as date)) between @startdate and @enddate


Group by firstname, lastname, f2.UserName, ScheduleID, f1.AgentID, f2.AgentID, StartDateTimeUTC, f3.UserId



Select *
From #boris5table

drop table #boris5table

0 个答案:

没有答案