我是SQL的初学者,我正在开发一个查询,为每个Provider(Employee)生成Open Appointment Time Slot。任何人都可以帮助以下查询?非常感谢你!
安排表样本数据:
ScheduleNum | ProvNum (Provider) | SchedDate | StartTime | EndTime
1 | 3 | 7/1/2017 | 8:00AM | 9:00 AM
2 | 3 | 7/1/2017 | 10:00AM | 11:00 AM
3 | 4 | 7/1/2017 | 8:00AM | 9:00 AM
4 | 4 | 7/1/2017 | 12:00PM | 1:00 PM
5 | 4 | 7/1/2017 | 3:00PM | 4:00 PM
打开约会查询表预期结果:
ProvNum (Provider) | SchedDate | avail_start_dt_time| avail_end_dt_time
3 | 7/1/2017 | 9:00 AM | 10:00 AM
4 | 7/1/2017 | 9:00 AM | 12:00 PM
4 | 7/1/2017 | 1:00 PM | 3:00 PM
查询我正在处理。
SELECT
avail.schedulenum
, avail.provnum
, avail.start_at as avail_start_dt_time
, avail.end_at as avail_end_dt_time
, avail.on_dt as just_date_no_time
, avail.starttime as prov_start_time
, avail.endtime as prov_end_time
FROM (
SELECT
dts.num, dts.on_dt, dts.start_at, dts.end_at, s.provnum, s.starttime, s.stoptime
FROM (
/* generates 1000, 10 minute "slots", starting at a variable date */
SELECT
schedulenum + 1 as num
, DATE_ADD(INTERVAL (slots.num * 10) MINUTE) start_at
, DATE_ADD(INTERVAL ((slots.num+ 1) * 10) MINUTE) end_at
FROM (
/* generates 1000 rows 0 to 999 */
SELECT hundreds.digit * 100 + tens.digit * 10 + ones.digit AS num
FROM (
SELECT 0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
) ones
CROSS JOIN (
SELECT 0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
) tens
CROSS JOIN (
SELECT 0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
) hundreds
) slots
) dts
INNER JOIN schedule s ON s.starttime < dts.end_at AND s.stoptime > dts.start_at
) avail
WHERE schedulenum IS NULL