我遇到了问题,不知道如何解决..
我有下一个查询和结果的图像。
SELECT SCH.DAY AS 'Day',
convert(char(5), SCH.START_TIME, 108) AS 'Start Time',
convert(char(5), SCH.END_TIME, 108) AS 'End time',
R.ROOM_NAME AS 'Classroom',
FROM SECTIONSCHEDULE SCH
INNER JOIN ROOM R ON SCH.ROOM_ID = R.ROOM_ID
WHERE R.ROOM_NAME = 'AU 401' AND SCH.DAY = 'MONDAY'
我所做的是获得课程,开始时间,结束时间以及课堂所在的课堂。我有两张桌子,在ROOM桌子上我只有Room_ID和房间的名字,而在另一张桌子上“SectionSchedule”我有一天,教室将被占用,课程开始的时间( SCH.Start_Time)和课程完成的时间(SCH.END_TIME)。 Start_Time和End_Time属于“DateTime”类型。所以,在下一张图片中,我将向您展示房间“AU 401”将被占用的时间。
但现在这是我存货的部分。我必须得到教室不会被占用的确切时间,因此您在上一张图片中看到教室将在下午14:05至下午17:05和下午20:47至22之间被占用:下午47点。学校的课程从上午07:00开始,所以我必须展示类似的内容:
07:00 AM至14:05 PM
下午17:05至20:47
下午22:47至24:00
但我不知道怎么做到这一点,我正在使用DateDifference,我得到了End_Time和Start_Time之间的区别,但我只得到“3小时”和“2小时”。所以我不确定如何得到我想要的东西。
¿有人可以帮帮我吗?
答案 0 :(得分:0)
这样做:
WITH cteNotEmpty
AS
(
SELECT
SCH.DAY AS 'Day',
convert(char(5), SCH.START_TIME, 108) AS 'StartTime',
convert(char(5), SCH.END_TIME, 108) AS 'EndTime',
R.ROOM_NAME AS 'Classroom',
FROM
SECTIONSCHEDULE SCH
JOIN ROOM R ON SCH.ROOM_ID = R.ROOM_ID
WHERE R.ROOM_NAME = 'AU 401' AND SCH.DAY = 'MONDAY'
)
SELECT
Q.[Day]
, Q.Classroom
,
CASE
WHEN L <> StartTime THEN L
WHEN L IS NULL AND StartTime <> '07:00:00' THEN '07:00:00'
ELSE NULL
END EmptyStartTime
,
CASE
WHEN L <> StartTime THEN StartTime
WHEN L IS NULL AND StartTime <> '07:00:00' THEN StartTime
ELSE NULL
END EmptyEndTime
FROM
(
SELECT
[Day]
, StartTime
, Classroom
, LAG(EndTime, 1, NULL) OVER (PARTITION BY [Day], Classroom ORDER BY EndTime) L
FROM cteNotEmpty
) Q
WHERE
CASE
WHEN L <> StartTime THEN L
WHEN L IS NULL AND StartTime <> '07:00:00' THEN '07:00:00'
ELSE NULL
END IS NOT NULL
UNION
SELECT
Q.[Day]
, Q.Classroom
,
CASE
WHEN L <> EndTime THEN EndTime
WHEN L IS NULL AND EndTime <> '23:59:59' THEN EndTime
ELSE NULL
END EmptyStartTime
,
CASE
WHEN L <> EndTime THEN L
WHEN L IS NULL AND EndTime <> '23:59:59' THEN '23:59:59'
ELSE NULL
END EmptyEndTime
FROM
(
SELECT
[Day]
, EndTime
, Classroom
, LEAD(StartTime, 1, NULL) OVER (PARTITION BY [Day], Classroom ORDER BY StartTime) L
FROM cteNotEmpty
) Q
WHERE
CASE
WHEN L <> EndTime THEN EndTime
WHEN L IS NULL AND EndTime <> '23:59:59' THEN EndTime
ELSE NULL
END IS NOT NULL
ORDER BY
[Day]
, Classroom
, EmptyStartTime