检查多个日程安排

时间:2015-06-12 21:09:17

标签: sql-server sql-server-2012

如果有人在工作,我想要查看一系列日期。

我希望看到每个人对每个日期的条目,如果它们不起作用则为null或零

E.g。如果日期是上周,6/1到6/7,那么我想看看

6/1 - Name1 - 1
6/2 - Name1 - 1
6/3 - Name1 - 1
6/4 - Name1 - 1
6/5 - Name1 - 1
6/6 - Name1 - 0
6/7 - Name1 - 0
6/1 - Name1 - 1
6/2 - Name1 - 1
6/3 - Name1 - 0
6/4 - Name1 - 0
6/5 - Name1 - 1
6/6 - Name1 - 1
6/7 - Name1 - 1

我尝试过左右连接,并且它似乎不起作用,因为所有日期都被使用,而不是每个人都使用。

到目前为止

代码:

declare @SchedWeek table
    (
    DateCode varchar(50) primary key
    --I wish I knew who decided the date would be varchar(50)
    )

insert into @schedweek
    (DateCode)
values
    ('20150601'),
    ('20150602'),
    ('20150603'),
    ('20150604'),
    ('20150605'),
    ('20150606'),
    ('20150607')

SELECT [@SchedWeek].[DateCode]
    ,a.* 
from @schedweek 
    left outer join (
    select distinct --because of multiple entries describing schedule in excruciating detail
           [schedDate]
          ,[ssn]
          ,[agentName]
          ,[externalID]
          ,muID 
    FROM [AgtScheduleDetail] ) a
    on [@SchedWeek].[DateCode]=[a].[scheddate] 

2 个答案:

答案 0 :(得分:0)

您是否考虑过创建DimDate表? Brent Ozar有一个很棒的视频和有关DimDate应用的更多信息。我必须这样做以确定一段时间/天的实用程序,并通过简单的交叉连接到DimDate,您可以完成您的查询。以下是我如何使用DimDate表编写它:

    SELECT employee_ID, dimdate.DATE_ID, 
CASE WHEN scheduleddate = dimdate.date_ID then 1 ELSE 0 END as [EmployeeActiveOnDay]
    FROM EmployeeSchedule
    CROSS JOIN dimdate

答案 1 :(得分:0)

使用您的代理列表,您可以将代理表交叉加入@SchedWeek表。然后使用它连接到您的AgtScheduleDetail表。与

类似
WITH cteAgentSchedule AS
(
    SELECT 
        DateCode,
        [agentName],
        [agentId]
    FROM
        @schedweek, [Agents] -- combine tables
)
SELECT
    a.DateCode,
    a.[agentName],
    (CASE WHEN asd.[agentId] IS NULL THEN 0 ELSE 1 END) [worked]
FROM
    cteAgentSchedule a
    left outer join (
        select distinct --because of multiple entries describing schedule in excruciating detail
               [agentId] -- added for join 
              ,[schedDate]
              ,[ssn]
              ,[agentName]
              ,[externalID]
              ,muID 
        FROM [AgtScheduleDetail] 
    ) asd on a.[agentId] = asd.[agentId] AND a.[DateCode] = asd.[scheddate]