这里有一个选项,使用一个CTE来处理数据,还有一个rank()和lead()函数。
WITH cteCourse
AS (SELECT 111 AS Id,
'Bio 101' AS Course_Name,
'1/10/2016' AS Course_Date,
'09:00:00' AS Course_Start_Time,
'09:45:00' AS Course_End_Time
UNION ALL
SELECT 111 AS Id,
'Bio 101' AS Course_Name,
'1/10/2016' AS Course_Date,
'10:00:00' AS Course_Start_Time,
'10:45:00' AS Course_End_Time
UNION ALL
SELECT 111 AS Id,
'Bio 101' AS Course_Name,
'1/10/2016' AS Course_Date,
'11:05:00' AS Course_Start_Time,
'12:30:00' AS Course_End_Time
UNION ALL
SELECT 431 AS Id,
'Econ 101' AS Course_Name,
'1/12/2016' AS Course_Date,
'11:00:00' AS Course_Start_Time,
'12:45:00' AS Course_End_Time
UNION ALL
SELECT 111 AS Id,
'Bio 101' AS Course_Name,
'1/12/2016' AS Course_Date,
'13:00:00' AS Course_Start_Time,
'14:45:00' AS Course_End_Time
UNION ALL
SELECT 543 AS Id,
'Eng 200' AS Course_Name,
'1/13/2016' AS Course_Date,
'14:00:00' AS Course_Start_Time,
'14:45:00' AS Course_End_Time
UNION ALL
SELECT 543 AS Id,
'Eng 200' AS Course_Name,
'1/13/2016' AS Course_Date,
'14:55:00' AS Course_Start_Time,
'15:55:00' AS Course_End_Time
UNION ALL
SELECT 543 AS Id,
'Eng 200' AS Course_Name,
'1/14/2016' AS Course_Date,
'18:00:00' AS Course_Start_Time,
'20:15:00' AS Course_End_Time)
SELECT Id,
Course_Name,
Course_Date,
Course_Start_Time,
Course_End_Time,
CASE
WHEN Course_End_Time + '00:30:00' <= LEAD(Course_Start_Time, 1, 0) OVER (ORDER BY Course_Name,
Course_Date,
Course_Start_Time,
Course_End_Time
) THEN
RANK() OVER (PARTITION BY Id,
Course_Date
ORDER BY Course_Start_Time,
Course_End_Time
)
ELSE
1
END AS GENERATED_SEQUENCE
FROM cteCourse;
回答下面的问题,您可以将第二个查询转换为CTE并像表一样从中进行查询。例如:
,cteGenSeq AS (
SELECT Id,
Course_Name,
Course_Date,
Course_Start_Time,
Course_End_Time,
CASE
WHEN Course_End_Time + '00:30:00' <= LEAD(Course_Start_Time, 1, 0) OVER (ORDER BY Course_Name,
Course_Date,
Course_Start_Time,
Course_End_Time
) THEN
RANK() OVER (PARTITION BY Id,
Course_Date
ORDER BY Course_Start_Time,
Course_End_Time
)
ELSE
1
END AS GENERATED_SEQUENCE
FROM cteCourse
)
SELECT * FROM cteGenSeq