我有这个SQL查询:
USE thr_clinic
GO
WITH CompleteSchedule AS (
SELECT U.ID as UserID, U.Role, U.Surname, U.Clinic, TS.ID as TimeSlotID, TS.TimeSlot
FROM Users U
CROSS JOIN TimeSlots TS
)
SELECT CS.*
FROM CompleteSchedule CS
LEFT JOIN Appointments A
ON A.MedicalStaffID = CS.UserID
AND A.TimeSlot = CS.TimeSlotID
AND A.AppDate = CONVERT(DATE,DATEADD(day, 3, GETDATE()))
WHERE A.ID is null
AND CS.Role != 'Patient'
AND CS.Clinic = (SELECT Clinic FROM Users WHERE Users.ID = 1)
AND CS.UserID != (SELECT StaffID FROM DaysOff WHERE DayOff = CONVERT(DATE,DATEADD(day, 3, GETDATE())))
ORDER BY CS.UserID, CS.TimeSlotID
然而,在WHERE
之前的ORDER BY
,如果返回空(意味着在给定日期没有人关闭),则整个查询不返回任何内容;但是如果有结果(有人关闭),他们就不会出现,其他人都会这样,并且工作正常。
我认为如果它返回为空则会显示所有人,因为空不是 userID 它无法显示。
答案 0 :(得分:3)
由于where子句中使用的子查询可能会返回多个值,因此您可能不应该使用!=
而是使用not in
:
AND CS.UserID NOT IN (SELECT StaffID FROM DaysOff WHERE DayOff
答案 1 :(得分:2)
所以你想知道为什么你的子查询返回NULL
的行没有?因为NULL
既不是=
也不是<>
。使用IS NULL
:
AND ((SELECT StaffID FROM DaysOff WHERE DayOff = CONVERT(DATE,DATEADD(day, 3, GETDATE()
IS NULL OR CS.UserID != (SELECT StaffID FROM DaysOff WHERE DayOff = CONVERT(DATE,DATEADD(day, 3, GETDATE()))))