1

我想在给定的计划日期显示所有可用用户(用户类型:员工)。如果两天都安排了,则不可用(下午/上午)

这是我的下表:

用户类型

TypeID     TypeName
1          Admin
2          Employee

用户

UserID     TypeID     Name
1          1          Admin 1
2          2          Employee 1
3          2          Employee 2
4          1          Admin 2
5          2          Employee 3
6          2          Employee 4
7          2          Employee 5

日程

SchedID   UserID      SchedDate     Day (PM/AM)
1         2           8/27/2013     PM
2         2           8/27/2013     AM
3         3           8/27/2013     AM
4         5           8/27/2013     PM
5         6           8/27/2013     AM

预期结果(其中 SchedDate='8/27/2013')

UserID    Name
3         Employee 2
5         Employee 3
6         Employee 4
7         Employee 5

这是我当前的 SQL 语句:

SELECT Users.UserID, Users.Name FROM Users LEFT OUTER JOIN 
Schedule ON Schedule.UserID = Users.UserID WHERE Users.TypeID = 5
4

2 回答 2

3

让我们换一种说法。如果用户同时为该DAY列安排了上午和下午,则该用户不可用。否则,用户可用。

鉴于该列中只有两个值,以下查询会执行您想要的过滤:

SELECT u.UserID, u.Name
FROM Users u LEFT OUTER JOIN 
     Schedule s
     ON s.UserID = u.UserID and
        s.ScheduleDate = '2013-08-27'
WHERE u.TypeID = 5
GROUP BY u.UserID, u.Name
HAVING COUNT(distinct s.day) < 2;

如果您知道这些值从不重复,则可以将having子句更改为:

HAVING COUNT(*) < 2;

这有点小技巧。当调度表中根本没有匹配时,计数将返回0(在第一种情况下)或1(在第二种情况下)。

于 2013-08-27T13:07:22.380 回答
1
SELECT USERS.USERID, 
       USERS.NAME 
FROM   USERS 
WHERE  NOT EXISTS (SELECT SCHEDID 
                   FROM   SCHEDULE 
                   WHERE  SCHEDULE.USERID = USERS.USERID 
                          AND DAY = 'AM') 
       AND NOT EXISTS (SELECT SCHEDID 
                       FROM   SCHEDULE 
                       WHERE  SCHEDULE.USERID = USERS.USERID 
                              AND DAY = 'PM') 
于 2013-08-27T13:05:36.120 回答