SQL Server查询以根据计划

时间:2016-05-22 19:01:14

标签: sql sql-server database

我有两个表,父表Employees和子表Employees_Availability,如下所示:

Employees表:

EmployeesID   Name     Group    Availability_Order  Available
--------------------------------------------------------------
     1        Steve    Sales            1           TRUE
     2        Ann      Sales            2           TRUE
     3        Jack     Sales            3           FALSE
     4        Sandy    Support          4           TRUE
     5        Bill     Support          5           TRUE
     6        John     Support          6           TRUE

Employees_Schedule表:

EmployeesID    Day             From     To  
----------------------------------------------
     1         Monday           8:00    12:00   
     1         Monday          13:00    17:00   
     2         Monday          12:00    13:00   
     3         Tuesday          7:30    11:30   
     3         Wednesday        7:30    11:30   
     3         Friday          14:30    16:30   
     4         Tuesday         11:30    17:00   
     5         Wednesday        8:00    12:00   
     5         Wednesday       13:00    17:00   
     5         Thursday        12:00    13:00   
     5         Friday           7:30    11:30   
     6         Friday          12:00    13:00   

如何创建一个给定日期/时间和Group返回第一个可用员工的查询?我正在使用SQL Server 2012.这是我开始做的但却陷入困境:

Select top 1 
    Name 
from 
    Empolyees e join? Employees_Schedule s 
on
    e.employeesID = s.EmployeesID 
where
    e.group = 'Sales' 
    and DATENAME(Weekday,'5/24/2016 10:00') = s.Day 
    and CAST('5/24/2016 10:00' AS TIME) 'hh:mm' >= CAST(s.from AS TIME)
    and CAST('5/24/2016 10:00' AS TIME) 'hh:mm' <= CAST(s.to AS TIME)
order by 
    e.availability_order  

由于

2 个答案:

答案 0 :(得分:0)

你看过Window Function和CTE吗?你可以轻松地实现这一目标,例如......

Row_Number() OVER(PARTITION BY day ORDER BY starttime ASC) as ColumnName

结合谓词

WHERE columnName = 1 AND groupName = 'groupname'

有关详细信息,请阅读OVER()条款here和CTE here上的BOL。

答案 1 :(得分:0)

看起来你很亲密。如果您将SQL的主要部分包装在Common Table Expression中并使用row_number() window function,那么您可以找到第一个可用的:

;with cte as (
 Select top 1 
     Name,
     row_number() over (order by ea.From) PrioritySequence
 from 
     Empolyees e join? Employees_Schedule s 
 on
     e.employeesID = s.EmployeesID 
 where
     e.group = 'Sales' 
     and DATENAME(Weekday,'5/24/2016 10:00') = s.Day 
     and CAST('5/24/2016 10:00' AS TIME) 'hh:mm' >= CAST(s.from AS TIME)
     and CAST('5/24/2016 10:00' AS TIME) 'hh:mm' <= CAST(s.to AS TIME)
)
select *
  from cte
 where PrioritySequence = 1