下面的 SQL 查询应该显示教师的可用性。有 3 种可能的预订类型 - 上午、下午或全天。如果有上午预订,则单元格中的文本应显示下午,如果有下午预订,则应显示上午,如果有全天预订,或上午和下午预订,则应显示“xxx”。
这在凌晨 1 点、下午 1 点或 1 全天预订时一切正常,但如果在同一天有凌晨 1 点和下午 1 点,它不会显示 XXX,因为我使用的是 MIN()。我怎样才能让它在一天内评估所有预订,而不是最小的预订?(你可以看到我试图在星期四的代码部分说明我的意思。
SQL:
with CTE_D as
(
SELECT
DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0) as BookingDate
UNION ALL
SELECT
DATEADD(day, 1, BookingDate)
FROM
CTE_D
WHERE
BookingDate < DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 6)
)
SELECT
t.ID, t.Firstname,
t.Surname, tb.Band, t.Telephone, t.Mobile, t.Teacher, t.TeacherAssistant, t.PrimarySchool, t.SecondarySchool,
MIN(CASE WHEN bd.DayText = 'Monday' AND bd.BookingDuration = 0 THEN 'PM' ELSE 'Full Day' END) "Monday",
MIN(CASE WHEN bd.DayText = 'Tuesday' AND bd.BookingDuration = 0 THEN 'PM' ELSE 'Full Day' END) "Tuesday",
MIN(CASE WHEN bd.DayText = 'Wednesday' AND bd.BookingDuration = 0 THEN 'PM' ELSE 'Full Day' END) "Wednesday",
MIN(CASE WHEN bd.DayText = 'Thursday' AND bd.BookingDuration = 0 THEN 'PM' WHEN bd.DayText = 'Thursday' AND bd.BookingDuration = 1 THEN 'AM' WHEN bd.DayText = 'Thursday' AND bd.BookingDuration = 2 or (bd.BookingDuration = 1 and bd.BookingDuration = 0) THEN 'xxx' END) "Thursday",
MIN(CASE WHEN bd.DayText = 'Friday' AND bd.BookingDuration = 0 THEN 'PM' ELSE 'Full Day' END) "Friday",
Notes
FROM Teachers t
cross join CTE_D d
left join BookingDays bd
on t.ID = bd.TeacherID and
bd.BookingDate = d.BookingDate
left join BookingDurations bds
on bd.BookingDuration = bds.ID
left join TeacherBands tb on t.Band = tb.ID
WHERE t.Active = 0 and (t.Status = 0 or t.Status = 1) and (bd.Status = 0 or bd.Status IS NULL) and PrimarySchool = 1
GROUP BY Firstname, Surname, t.Telephone, t.Mobile, t.Notes, tb.Band, t.ID, t.Teacher, t.TeacherAssistant, t.PrimarySchool, t.SecondarySchool, t.Nursery, t.Reception, t.Year1, t.Year2, t.Year3, t.Year4, t.Year5, t.Year6, t.Year7, t.Year8, t.Year9, t.Year10, t.Year11, t.ALevel
ORDER BY Surname, Firstname ASC
表列:
ID | Firstname | Surname | Band | Telephone | Mobile | Teacher | Teacher Assistant | PrimarySchool | SecondarySchool | KeyStage | Mon | Tues | Wed | Thurs | Fri | Notes
谢谢,马特