1

我有以下返回 2 行的 SQL 语句(预订天数)

SELECT bd.ID, t.FirstName, t.Surname, 
CASE WHEN bd.BookingDuration = 3 AND CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') AND bd.NoOfHOurs < 5.5 THEN bd.ID ELSE NULL END as 'TuesdayHourlyAM',
CASE WHEN bd.BookingDuration = 3 AND CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') AND bd.NoOfHOurs < 5.5 THEN bd.ID ELSE NULL END as 'TuesdayHourlyAM2'
from BookingDays bd join
(
    select ID, MIN(StartTime) as minx, MAX(StartTime) as maxx
    from BookingDays
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0
    group by ID
) 
tmin
on bd.ID = tmin.ID and bd.StartTime = tmin.minx

inner join Teachers t on bd.TeacherID = t.ID
where t.Surname = 'cairns'
group by bd.ID, bd.StartTime, bd.DayText, t.Firstname, t.Surname, bd.BookingDate,       bd.BookingDuration, bd.NoOfHours, tmin.minx, tmin.maxx

这返回 -

需要合并为一的 2 行的屏幕截图

我正在寻找的是具有类似格式的表格,但是在 1 行中:

名字 | 姓氏 | 星期二每小时AM1 | 星期二每小时上午1 开始 | 星期二每小时上午1 结束 | 星期二每小时AM2 | 星期二每小时上午2 开始 | 星期二每小时上午 2 结束

TuesdayHourlyAM1:BookingDayID TuesdayHourlyAM2:BookingDayID 开始/结束:预订的开始和结束时间

其中 AM1 是最短开始时间,AM2 是最长开始时间(此标准的预订天数永远不会超过 2 个)。

4

2 回答 2

1
SELECT t.FirstName, t.Surname, tmin.id as TuesdayHourlyAM1, tmin.StartTime as TuesdayHourlyAM1Start, tmin.Endtime as  TuesdayHourlyAM1End ,
tmax.id as TuesdayHourlyAM2, tmax.StartTime as TuesdayHourlyAM2Start, tmax.Endtime as  TuesdayHourlyAM2End
Teachers t inner join 
from 
(
    select top 1 id, bd.teacherID MIN(StartTime) as StartTime, endtime as Endtime
    from BookingDays  bd inner join Teachers t on bd.TeacherID = t.ID
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0  and t.Surname = 'cairns'
    group by id,endtime, bd.teacherID
        order by StartTime asc
) 
tmin 
on  t.id = tmin.teacherID
join
(
    select top 1 id, bd.teacherID, max(StartTime) as StartTime, endtime as Endtime
     from BookingDays  bd inner join Teachers t on bd.TeacherID = t.ID
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0 and t.Surname = 'cairns'
    group by id,endtime, bd.teacherID
    order by StartTime desc

) 
tmax
 on  t.id = tmax.teacherID
于 2013-06-24T10:59:27.947 回答
1

尝试按teacherid而不是bookingid对子查询进行分组

SELECT t.FirstName, t.Surname, minx as TuesdayHourlyAM1, maxx as TuesdayHourlyAM2
from BookingDays bd join
(
    select TeacherID, MIN(StartTime) as minx, MAX(StartTime) as maxx
    from BookingDays
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0
    group by TeacherID
) 
tmin
on bd.teacherID = tmin.ID and bd.StartTime = tmin.minx

inner join Teachers t on bd.TeacherID = t.ID
where t.Surname = 'cairns'
于 2013-06-24T09:45:15.447 回答