使用SQL 15.0.2000.5版
我有一个表格,里面有这些数据:
StudentScheduleId | Monday | Tuesday | Wednesday | Thursday | Friday | MondayStartTime | MondayEndTime | TuesdayStartTime | TuesdayEndTime | WednesdayStartTime | WednesdayEndTime | ThursdayStartTime | ThursdayEndTime | FridayStartTime | FridayEndTime |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15 | 1 | 1 | 1 | 1 | NULL | 9:00 | 11:00 | 11:00 | 12:30 | 9:00 | 11:00 | 11:00 | 12:30 | NULL | NULL |
31 | 1 | NULL | NULL | 1 | 0 | 2:00 | 3:15 | NULL | NULL | NULL | NULL | 2:00 | 3:15 | NULL | NULL |
我想实现这样的格式:
StudentScheduleId | Schedule | StartTime | EndTime |
---|---|---|---|
15 | T/Th | 11:00 | 12:30 |
15 | M/W | 9:00 | 11:00 |
31 | M | 9:00 | 11:00 |
我可以使用这个查询来做到这一点:
Select s.StudentScheduleId,
STRING_AGG(s.[Day], '/') AS Schedule,
s.StartTime,
s.EndTime
From
(
(Select s.StudentScheduleId, 'M' As [Day], s.MondayStartTime As StartTime, s.MondayEndTime As EndTime
From StudentSchedule s
Where s.Monday = 1)
UNION
(Select s.StudentScheduleId, 'T' As [Day], s.TuesDayStartTime As StartTime, s.TuesdayEndTime As EndTime
From StudentSchedule s
Where s.Tuesday = 1)
UNION
(Select s.StudentScheduleId, 'W' As [Day], s.WednesdayStartTime As StartTime, s.WednesdayEndTime As EndTime
From StudentSchedule s
Where s.Wednesday = 1)
UNION
(Select s.StudentScheduleId, 'Th' As [Day], s.ThursdayStartTime As StartTime, s.ThursdayEndTime As EndTime
From StudentSchedule s
Where s.Thursday = 1)
UNION
(Select s.StudentScheduleId, 'F' As [Day], s.FridayStartTime As StartTime, s.FridayEndTime As EndTime
From StudentSchedule s
Where s.Friday = 1)
) As s
Group By s.StudentScheduleId, s.StartTime, s.EndTime
然而,我对结果有一个担忧,也有一个问题.
- 有没有更好更熟练的方法来做到这一点考虑到性能或只是更简洁? 我不指望这个表会有数百万条记录,但我可以看到它最终会增长到100万条.
- 我测试了其他场景,使用一周中的更多天,具有相同的开始和结束时间,并且日程列结果可以以任何顺序出现. (例如:F/M/T/Th/W). 我希望这是以逻辑顺序M/T/W/Th/F出来的. 我知道strING_AGG的PROCEIN GROUP排序,但没有什么可排序的,或者我需要添加一个排序列,有什么 idea 吗?
谢谢你的帮助!